我开发学习解析数据以及如何处理同步和异步请求。
NSString *url=@"http://content.guardianapis.com/search?api-key=test";
NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:url]];
NSError *error=nil;
NSURLResponse *response;
NSData *content=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *string=[[NSString alloc]initWithData:content encoding:NSUTF8StringEncoding];
NSLog(@"response %@",string);
我在sendSynchronousRequest
行收到警告。如何处理此异步Web请求并获取响应数据。解释两者的区别。
答案 0 :(得分:0)
这里有两个不同的问题。
首先,请求应该是异步的,并使用NSURLSession
。例如:
NSURL *url = [NSURL URLWithString:@"http://content.guardianapis.com/search?api-key=test"];
NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error) {
NSLog(@"%@", error);
return;
}
NSError *parseError;
NSDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
if (responseObject) {
NSLog(@"%@", responseObject);
dispatch_async(dispatch_get_main_queue(), {
// if you want to update your UI or any model objects,
// do that here, dispatched back to the main queue.
});
} else {
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"problem parsing response, it was:\n%@", string);
}
}];
[task resume];
// but do not try to use `data` here, as the above runs asynchronously
// do everything contingent upon this request _inside_ the completion
// handler above
注意,当您收到JSON响应时,可以使用NSJSONSerialization
解析该响应,如上所示。
如今,使用http
请求是不受欢迎的,因为它不安全。您通常应该使用https
。 NSURLSession
会强制执行此操作,如果您尝试使用http
,则会返回错误。但是,如果您要强制它允许不安全的http
请求,则必须使用以下条目更新info.plist
:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>guardianapis.com</key>
<dict>
<!--Include to allow subdomains-->
<key>NSIncludesSubdomains</key>
<true/>
<!--Include to allow HTTP requests-->
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
<!--Include to specify minimum TLS version-->
<key>NSTemporaryExceptionMinimumTLSVersion</key>
<string>TLSv1.1</string>
</dict>
</dict>
</dict>
所以,转到你的info.plist
,控件 - 点击它并选择&#34; Open As&#34; ......&#34;源代码&#34;然后将上面的内容添加到其中。有关详细信息,请参阅https://stackoverflow.com/a/31254874/1271826。