【问题标题】:NSHTTPURLResponse is nil but no NSError is generatedNSHTTPURLResponse 为 nil 但未生成 NSError
【发布时间】:2017-12-19 19:26:54
【问题描述】:

我正在尝试读取NSHTTPURLResponse 状态代码,但是NSHTTPURLResponse 返回nil,但没有创建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;
}

【问题讨论】:

    标签: ios objective-c objective-c-blocks nsurlsession nserror


    【解决方案1】:

    这在 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 更有意义的东西,但它说明了这个想法:不要尝试在不采用异步模式的情况下从异步方法返回值(例如完成处理程序)。

    【讨论】:

    • 谢谢!感谢您抽出时间来帮助我,并向我展示一种新模式!
    猜你喜欢
    • 1970-01-01
    • 2015-09-24
    • 2018-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多