先进行请求
-(void)startRequest:(NSString *)str{
NSString *news_id = str;
NSScanner *scan = [NSScanner scannerWithString:news_id];
int val;
if([scan scanInt:&val]&&[scan isAtEnd]){
NSString *news_url =[[NSString alloc] initWithFormat:@"http://xxxxxxxxxxxxxxxxxxxxxxxxx.php?id=%@",news_id];
NSURL *url = [NSURL URLWithString:news_url];NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connection) {
datas = [NSMutableData new];
}
}
}
#pragma mark- NSURLConnection 回调方法
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[datas appendData:data];
}
-(void) connection:(NSURLConnection *)connection didFailWithError: (NSError *)error {
NSLog(@"%@",[error localizedDescription]);
}
- (void) connectionDidFinishLoading: (NSURLConnection*) connection {
//其中datas需要进行转码
NSLog(@"datas%@",[[NSString alloc] initWithData:datas encoding:(NSUTF8StringEncoding)]);
。。。。。。。。。
接下来就是对你接收到的datas进行转码
专门封装一个类,队请求回来的数据进行整理
在这个类中需要有我的这个封装的类叫News*
+(News*)initNewsWithId:(NSData*)datas
{//利用ios自带的json对请求返回的数据进行解析
NSDictionary* dict = [NSJSONSerialization JSONObjectWithData:datas
options:NSJSONReadingAllowFragments error:nil];
if ([dict isKindOfClass:[NSNull class]])
return NULL;
News *news = [[News alloc] init];
下面对news类里面的每一个成员进行复制,形如:
news.nId =[dict objectForKey:@"id"];
。。。。。。。。。
return news;
}
//下面是必须有的,进行转码的过程,不然的话会报错
-(void)encodeWithCoder:(NSCoder *)encoder
{
形如:
[encoder encodeObject:nId forKey:@"nId"];
}
-(id)initWithCoder:(NSCoder *)decoder
{
形如:
self.nId=[decoder decodeObjectForKey:@"nId"];
return self;
}
@end
自己觉得如果对数据解析要求不太高,用ios自带的类解析不错!