范例(从本地服务器获取数据打印出来):
//确定url
NSURL *url = [NSURL URLWithString:@"http://127.0.0.1/demo.json"];
//建立请求(参数:资源路径、缓存策略、超时期限,默认60s)
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:15 ];
//建立connection,发送请求到服务器
[NSURLConnection sendAsynchoronousRequest:request queue:
[[NSOperationQueue alloc] init] completionHandler:
^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
if(connectionError || data == nil)
{
NSLog(@"网络出错,稍后再试");
return;
}
//把数据显示出来
NSLog[@"%@", [[NSString alloc]
initWithData:data encoding:NSUTF8StringEncoding]);
//JSON解析数据(JSON的反序列化)
id result1 = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers error:NULL];
//JSONKit解析
id result2 = [[JSONDecoder decoder] objectWithData:data];
//Plist的反序列化
id result3 = [NSPropertyListSerialization propertyListWithData:data
options:0 format:NULL error:NULL];
NSLog(@"result = %@", result);
}];
注意:url中不能有中文或者空格之类的特殊符号,为了以防万一,最好用百分号转义
urlString = [rulString stringByAddingPercengtEscapesUsingEncoding:NSUTF8StringEncoding];