传递委托作为NSURLSession的参数

时间:2016-02-16 15:14:27

标签: ios objective-c

我有一个名为RestService的类,我在我的应用程序中使用它来对Web服务执行多个同步请求。我在这个类中添加了一个新方法来执行异步请求,我再次想要在我的应用程序中重用它。这是该新方法的代码:

- (void)backgroundExecutionOfService:(NSString *)serviceName 
                      withParameters:(NSDictionary *)parameters
                              inView:(UIView *)view
                        withDelegate:(UIViewController *)delegate
{
    NSString *serviceUrl = @"http://MyWebServer/public/api/clients/5";
    NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
    sessionConfig.allowsCellularAccess          = YES;
    sessionConfig.timeoutIntervalForRequest     = 10;
    sessionConfig.timeoutIntervalForResource    = 10;
    sessionConfig.HTTPMaximumConnectionsPerHost =  1;

    NSURLSession *session;
    session = [NSURLSession sessionWithConfiguration:sessionConfig
                                            delegate:delegate
                                       delegateQueue:nil];

    NSURLSessionDownloadTask *getFileTask;
    getFileTask = [session downloadTaskWithURL:[NSURL URLWithString:serviceUrl]];
    [getFileTask resume];
}

但是XCode正在给我一个关于将该参数用作委托的警告(发送UIViewController * __strong'到不兼容类型的参数' id< NSURLSessionDelegate> _Nullable')。我确保我作为参数发送的视图控制器声明了< NSURLSessionDelegate>在.h和我在ViewControllers的实现文件中创建了委托方法。

- (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(nullable NSError *)error{
    NSLog(@"Became invalid with error: %@", [error localizedDescription]);
}

- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
 completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * __nullable credential))completionHandler{
    NSLog(@"Received challenge");
}

- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session{
    NSLog(@"Did finish events for session: %@", session);
}

应用程序没有崩溃,但从不调用委托方法。同步Web服务按预期工作。

1 个答案:

答案 0 :(得分:1)

之所以发生这种情况,是因为UIViewController类不符合NSURLSessionDelegate协议。 要解决这种差异,只需将方法的签名更改为:

- (void)backgroundExecutionOfService:(NSString *)serviceName withParameters:(NSDictionary *)parameters inView:(UIView *)view withDelegate:(id<NSURLSessionDelegate>)delegate{
//... your code
}

并“阅读代表的基本知识。”