2017-10-03 17 views
-1
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]; 
} 

答えて

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{ 

} 
+0

デリゲートを追加しても違いはありません。 問題はiOS X Simulatorでのみ発生します。 NSURLSession * defaultSession = [NSURLSession sessionWithConfiguration:defaultConfigObject]を使用するとうまく動作します。その後の初めてのみNSURLSession * defaultSession = [NSURLSession sessionWithConfiguration:defaultConfigObjectデリゲート:nil delegateQueue:[NSOperationQueue mainQueue]]; はうまく機能しています –

0

初めて呼び出さ得ていません。 resume()メソッドを使用して手動でデータタスクを開始する必要があります。

tryブロック内でdataTaskオブジェクトを使用しないでください。

+0

問題はIPHONE X SIMULATORのみです。私はビルドの設定で何かを変更する必要があります。 Iは、トライキャッチブロック NSURLSessionDataTask * dataTask = [defaultSession dataTaskWithRequest:completionHandler要求:^(のNSData *データ、NSURLResponse *応答、NSError *エラー){ // を}]以下のように手動で再開を使用しても削除しています。 [dataTask resume]; } –

関連する問題