Проблема производительности внедрения NSURLSession

В моем приложении от 10 до 30 веб-сервисов (оба получают / отправляют). Ранее я использовал Async NSURLconnection. Это занимает около 5 секунд, чтобы оправдать все услуги. Но теперь я заменил NSurlsession, который получает задержку ответа по сравнению с nsurlconnection, он задерживается в 4-6 раз. здесь я приложил один из кода метода веб-сервиса для справки. как ниже у меня есть код для всех методов.

Пример кода NSURLsession

#pragma mark - NSURLSession

- (NSURLSession *)createSession
{
    NSLog(@"DSCReturnAPI: %s",__func__);

    static NSURLSession *session = nil;

    NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];

    sessionConfig.timeoutIntervalForRequest = WEBSERVICE_TIMEOUT;

    session = [NSURLSession sessionWithConfiguration:sessionConfig
                                            delegate:self
                                       delegateQueue:[NSOperationQueue mainQueue]];


    return session;
}


#pragma mark - API Callbacks
-(void)getMyData{
     @try {
        _webServieRequestType = HWDSCReturnGetRequestType;

        NSString *countrycode               =   [BusinessManager sharedInstance].countryCode;//[HWUserDefaults countryCode];
        NSString *userid                    =   [BusinessManager sharedInstance].userId;// [HWUserDefaults userId];
        NSString *accessToken               =   [BusinessManager sharedInstance].accessToken;//[HWUserDefaults accessToken];
        NSString *deviceId                  =   [HWUserDefaults deviceId];
        [HelperCallbacks logText:[NSString stringWithFormat:@"AccessToken %@",accessToken]];

        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        [request setURL:[NSURL URLWithString:API_DSCRETURN(countrycode,userid)]];
        [request setHTTPMethod:@"GET"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [request setValue:accessToken forHTTPHeaderField:@"Authorization"];
        [request setValue:deviceId forHTTPHeaderField:@"deviceId"];
        [request setValue:@"ba598025146eff37e26c9150b180a78b" forHTTPHeaderField:@"If-None-Match"];

        theSession = [self createSession];
        theDataTask = [theSession dataTaskWithRequest:request];

        [theDataTask resume];


    }
    @catch (NSException *exception) {
        [ExceptionHandler sendException:exception];
    }
}


#pragma mark - NSURLSessionDataDelegate

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
    didReceiveData:(NSData *)data {
    NSLog(@"DSCReturnAPI: %s",__func__);

    //    NSArray *dataArray = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];


    if (theSession == session) {
        if (_receivedData == nil) {
            _receivedData = [[NSMutableData alloc] initWithData:data];
        } else {
            [_receivedData appendData:data];

        }
    }
    else
    {
        //NSLog(@"");
    }
     }

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response  completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler {
    NSLog(@"DSCReturnAPI: %s",__func__);


    if (theSession == session) {
        [BusinessManager sharedInstance].urlResponseRecieved = NO;
        NSLog(@"DSCReturnAPI: httpResponse:%@",response);
        NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
        httpStatusCode =(int) [httpResponse statusCode]; // To track response Code:
        NSLog(@"DSCReturnAPI : Http code:%d",httpStatusCode);
        NSLog(@"DSCReturnAPI : Headers %@",[httpResponse allHeaderFields]);
        _receivedData = [[NSMutableData alloc]init];    }
       completionHandler(NSURLSessionResponseAllow);
     } 
#pragma mark - NSURLSessionTaskDelegate

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
    NSLog(@"DSCReturnAPI: %s",__func__);



    NSLog(@"DSCReturnAPI: didFailWithError :error : %@ errorCode: %ld",error.description,(long)error.code);
    @try {

        if ([self.serviceDelegate conformsToProtocol:@protocol(ServiceMgrProtocol)] && [self.serviceDelegate respondsToSelector:@selector(webServiceDidFailDSCReturnWithError:)]&& error.code != 0) {
            [self.serviceDelegate webServiceDidFailDSCReturnWithError:error.localizedDescription];
        }
        else {
            NSLog(@"DSCReturnAPI:SUCCESS");
            [self processResponse];

        }

        }
    @catch (NSException *exception) {
        [ExceptionHandler sendException:exception];
    }
    @finally {
        if (theSession) {
            theSession = nil;
        }
        _receivedData = nil;
    } }

1 ответ

Я думаю, что нет необходимости идти на такие методы NSURLSession, У него есть собственный блок, который работает в основном потоке.

NSMutableURLRequest *request =[[NSMutableURLRequest alloc] initWithURL:requestURL];

        NSLog(@"fetchAPromotionWithType = %@", requestURL);
        [request setHTTPMethod:@"GET"];

        NSURLSession *session = [NSURLSession sharedSession];
        NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                                completionHandler:
                                      ^(NSData *data, NSURLResponse *response, NSError *error)
                                      {

                                          dispatch_async(dispatch_get_main_queue(), ^{


                                              NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
                                              int responseStatusCode = (int)[httpResponse statusCode];

                                              if ( responseStatusCode == OK_RESPONSE_CODE || responseStatusCode == CREATED_RESPONSE_CODE || responseStatusCode == ACCEPTED_RESPONSE_CODE || responseStatusCode == PARTIAL_RESPONSE_CODE)
                                              {
                                                  if (data)
                                                  {
                                                      NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
                                                      NSLog(@"Data->%@",dict);

                                                      if (dict != nil && [dict isKindOfClass:[NSDictionary class]])
                                                      {
                                                          NSDictionary *dataDict = [dict objectForKey:@"data"];

                                                          if (dataDict != nil && [dataDict isKindOfClass:[NSDictionary class]])
                                                          {
                                                              //Get your success Data
                                                          }
                                                      }
                                                  }
                                              }
                                              else
                                              {
                                                  if (responseStatusCode == 0)
                                                  {
                                                      NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"No Connection! Please try again.", @"message", nil];
                                                      //Get Your Fail Data
                                                  }
                                                  else if (data)
                                                  {
                                                      // NSArray *tempArray = @[@"fan", @"vungle"];
                                                      //[JLSharedData sharedManager].savedWaterfallInterstitialArray = nil; //testing

                                                      NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
                                                      //Get Your Fail Data
                                                  }
                                              }

                                          });

                                      }];

        [task resume];
    }];
Другие вопросы по тегам