iOS9获取所在城市的接口及解析(简单的NSURLSession使用和新的编码方法使用)
/* 定位当前城市的方法调用 */
[self asynGETJSONWithURL:@"http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js" completion:^(id result) {
NSLog(@"%@", result[@"city"]);
}];
/* 方法实现 */
- (void)asynGETJSONWithURL:(NSString *)urlString completion:(void(^)(id result))block {
/* 1.转码 */
NSString *enCodingStr = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
/* 2.创建URL对象 */
NSURL *url = [NSURL URLWithString:enCodingStr];
/* 3.创建请求 */
NSURLRequest *request = [NSURLRequest requestWithURL:url];
/* 4.创建链接接受数据 */
NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
/* 5.数据解析 */
NSString *temResult = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if (temResult.length == 0) {
return ;
}
temResult = [temResult substringFromIndex:21];
temResult = [temResult substringToIndex:temResult.length - 1];
NSData* xmlData = [temResult dataUsingEncoding:NSUTF8StringEncoding];
id result = [NSJSONSerialization JSONObjectWithData:xmlData options:NSJSONReadingMutableContainers error:&error];
/* 6.通过block将result值返回出去 */
block(result);
}];
[task resume];
}