NSURLSessionDataTask完成处理程序第一次没有被调用

时间:2017-10-03 11:59:35

标签: ios objective-c

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-type"];
[request setHTTPBody:jsonData];

// configure NSURLSessionConfiguration with request timeout
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
// set request timeout
defaultConfigObject.timeoutIntervalForRequest  = 120.0;

// create NSURLSession object

// Working fine with below instance of default session but its taking a lot  of time to fetch response.
//NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultConfigObject];

NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];

// set NSURLSessionDataTask

@try {
      NSURLSessionDataTask * dataTask = [defaultSession dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
          //
      }]; 
      [dataTask resume];
}

2 个答案:

答案 0 :(得分:0)

   if ([self checkNetworkStatus]) {
        @try {
            // Create the data and url
            NSString *encryptedString = [self createRequest:userContext objectType:deviceObjectType projectType:projectId];
            NSDictionary *dictRequest = @{REQ_KEY_REQUEST: encryptedString};
            requestString = [JSONHelper dictionaryToJson:dictRequest];
            NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@Data",globals.API_Base_URL]];

            // Create Request
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.0];
            request.HTTPMethod = @"POST";    // For Post
            [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
            [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
            int strLength = (int)requestString.length;
            [request setValue:[NSString stringWithFormat:@"%d", strLength] forHTTPHeaderField:@"Content-Length"];

            NSData *dataRequest = [requestString dataUsingEncoding:NSUTF8StringEncoding];
            request.HTTPBody = dataRequest;`enter code here`

            id delegateValue = self;
           NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]
                                                    delegate:delegateValue
                                               delegateQueue:[NSOperationQueue mainQueue]];

           //NSURLSession *session = [NSURLSession sharedSession];
            NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                                    completionHandler:
                                          ^(NSData *responseData, NSURLResponse *response, NSError *error) {
                                              // ...
                                              [self destroyNetworkCache];
                                             // [[NSURLCache sharedURLCache] storeCachedResponse:nil forRequest:urlReq];
                                              [[NSURLCache sharedURLCache] removeAllCachedResponses];

                                              dispatch_async(dispatch_get_main_queue(), ^(void)
                                                             {
                                                                 if (! error)
                                                                 {
                                                                     [self parseResponse:responseData forObjectType:deviceObjectType andTag:tag withDelegate:del];
                                                                 }
                                                                 else
                                                                 {
                                                                     NSString *errMsg = error.description;
                                                                     if (errMsg.length <= 0) {
                                                                         errMsg = NSLocalizedString(@"msg_network_error", @"msg_network_error");
                                                                     }
                                                                     else if (errMsg.length > 0 && [errMsg rangeOfString:@"timed out"].length != 0)
                                                                     {
                                                                         errMsg = NSLocalizedString(@"msg_request_timed_out", @"msg_request_timed_out");
                                                                     }
                                                                     else if ([self checkForURLDomainError:errMsg])
                                                                     {
                                                                         errMsg = NSLocalizedString(@"msg_network_error", @"msg_network_error");
                                                                     }
                                                                     if (tag < 0)
                                                                     {
                                                                         if ([del conformsToProtocol:@protocol(WTConnectionServiceDelegate)])
                                                                         {
                                                                             if ([del respondsToSelector:@selector(wtConnectionService:forObjectType:didFailedWithError:)])
                                                                             {
                                                                                 [del wtConnectionService:nil forObjectType:deviceObjectType didFailedWithError:errMsg];
                                                                                 return;
                                                                             }
                                                                         }
                                                                     }
                                                                     else
                                                                     {
                                                                         if ([del conformsToProtocol:@protocol(WTConnectionServiceDelegate)])
                                                                         {
                                                                             if ([del respondsToSelector:@selector(wtConnectionService:forObjectType:andTag:didFailedWithError:)])
                                                                             {
                                                                                 [del wtConnectionService:nil forObjectType:deviceObjectType andTag:tag didFailedWithError:errMsg];
                                                                                 return;
                                                                             }
                                                                         }
                                                                     }

                                                                 }
                                                             });

                                          }];
            [task resume];

        }
        @catch (NSException *exception) {
            [self handleException:exception];
        }
        @finally {

        }
    }

Below Is delegate methods  

-(void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
{
    completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
}
-(void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(NSError *)error{

}

答案 1 :(得分:0)

任务永远不会完成,因为它永远不会开始。您必须使用resume()方法手动启动数据任务。

并且不要在try块中使用dataTask对象。