我正在尝试读取NSHTTPURLResponse状态代码,但是NSHTTPURLResponse返回的是零,但是没有创建NSError。
这个在iOS 11之前就已经开始工作了,但是我没有收到任何警告说它是不推荐的,而且我也找不到任何关于这个问题的在线参考NSURLSession。
知道为什么吗?
我通常将以下方法称为[MyClass getHTTPResponseRequest:@"http://www.google.com/"];
+ (NSInteger) getHTTPResponseRequest : (NSString*) testURL {
__block NSHTTPURLResponse * r = nil;
[[[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithString:testURL]
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(@"Error %@", error.localizedDescription);
}
r = (NSHTTPURLResponse *)response;
}] resume];
if(r == nil){
NSLog(@"Response is nil");
return 9999;
}
return r.statusCode;
}发布于 2017-12-19 19:47:40
这在iOS 11之前也是行不通的。dataTaskWithURL完成处理程序是异步调用的,但在尝试返回statusCode之前,不需要等待请求完成。
您应该采用异步模式,例如自己使用完成处理程序模式:
+ (void)getHTTPResponseRequestWithURL:(NSString *)urlString completion:(void(^ _Nonnull)(NSInteger))completion {
NSURL *url = [NSURL URLWithString:urlString];
[[[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(@"Error %@", error.localizedDescription);
}
NSInteger statusCode;
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
statusCode = [(NSHTTPURLResponse *)response statusCode];
} else {
statusCode = 9999;
}
completion(statusCode);
}] resume];
}你会把它叫做:
[MyClass getHTTPResponseRequestWithURL:@"http://google.com" completion:^(NSInteger statusCode) {
// examine the `statusCode` here
NSLog(@"%ld", (long)statusCode);
}];
// but the above runs asynchronously, so you won't have `statusCode` here现在,您的完成处理程序参数通常比整数statusCode返回更有意义的内容,但它说明了这样的想法:不要尝试在不使用异步模式(例如完成处理程序)的情况下从异步方法返回值。
https://stackoverflow.com/questions/47893916
复制相似问题