简体   繁体   中英

Completion handlers not working when calling Objective C code in AFNetworking

I have the following code from swift 3 which calls AFNetworking code

typealias StartSessionTaskHandler = (_ task: URLSessionDataTask) -> Void
typealias RetrySessionTaskHandler = (_ newTask: URLSessionDataTask) -> Void
typealias SuccessResponseHandler = (_ task: URLSessionDataTask, _ result: AnyObject) -> Void
typealias FailureResponseHandler = (_ task: URLSessionDataTask?, _ error: NSError) -> Void


  fileprivate func POST(_ service: AFHTTPSessionManager, URLString: String, parameters: AnyObject?, handleAuthorization: Bool, start: StartSessionTaskHandler?, retry: RetrySessionTaskHandler?, success:SuccessResponseHandler?, failure: FailureResponseHandler?) {

    /*
    First, prepare the call
    */

    print("*^*^*")
    print(parameters!)

    initiateSessionTaskWithAuthorization(handleAuthorization, failure: failure) {
        /*
        The session task is successfully initiated. Do the actual API call
        */
        let task = service.post(URLString, parameters: parameters, progress: nil, success: success as? ((URLSessionDataTask, Any) -> Void),

                                failure: {

                                    (task: URLSessionDataTask?, error: Error) in

                                    /*
                                    Try to handle the failure automatically
                                    */
                                    self.handleFailureForSessionTask(task, error: error as NSError, handleAuthorizationFailure: handleAuthorization, retry: retry, failure: failure,

                                        newTaskRetrieval: {

                                            /*
                                            This closure creates a copy of the original API call, but with the external failure handler (to avoid potential loops). It is used if we need to retry the original API call
                                            */
                                            return service.post(URLString, parameters: parameters as! [AnyObject], progress: nil, success: success as! ((URLSessionDataTask, Any) -> Void), failure: failure as! ((URLSessionDataTask?, Error) -> Void)? )
                                    })
        })

        /*
         The task is successfully started
         */
        if let task = task {//
            start?(task)
        }
    }
}

This will call the POST function from AFnetwroking which is defined as this

   - (NSURLSessionDataTask *)POST:(NSString *)URLString
                parameters:(id)parameters
                  progress:(void (^)(NSProgress * _Nonnull))uploadProgress
                   success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success
                   failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
   {

   NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"POST" URLString:URLString parameters:parameters uploadProgress:uploadProgress downloadProgress:nil success:success failure:failure];

      [dataTask resume];

      return dataTask;
  }

This internally calls the datataskwithhttpmethod which returns success or failure based on the response from the service It is defined as follows

   - (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method
                                   URLString:(NSString *)URLString
                                  parameters:(id)parameters
                              uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress
                            downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress
                                     success:(void (^)(NSURLSessionDataTask *, id))success
                                     failure:(void (^)(NSURLSessionDataTask *, NSError *))failure

   {
    NSError *serializationError = nil;
   NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError];
if (serializationError) {
    if (failure) {
        dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
            failure(nil, serializationError);
        });
    }

    return nil;
}

__block NSURLSessionDataTask *dataTask = nil;
dataTask = [self dataTaskWithRequest:request
                      uploadProgress:uploadProgress
                    downloadProgress:downloadProgress
                   completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) {
    if (error) {
        if (failure) {
            failure(dataTask, error);
        }
    } else {
        if (success) {
            success(dataTask, responseObject);            }
    }
}];

return dataTask;
}

When I try to return the success block back it is shown as NULL and it fails to return a response back to the swift code. This is not working from swift 3. Any help is appreciated. Thanks.

方法initiateSessionTaskWithAuthorization需要一个完成处理程序,您必须将其传递给service.post(...success:HERE)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM