NSURLSession 需要太多时间

NSURLSession takes too much time

我正在使用 NSURLSession 来 post 一个请求。虽然我将队列设置为主队列,但响应时间仍然过长

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

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:LOGIN_SERVICE]];

[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPMethod:@"POST"];

NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request];

[dataTask resume];

有一个类似的 question 但它只有一个答案与我正在做的相似。我遗漏了什么吗?

当您用所需的代码更新问题时,我不会在这里明显地说什么会使您的请求变慢,因为这是网络请求,所以很少有东西,这将取决于网络速度、服务器响应时间等不同的东西。在不同的网络设备上进行测试是值得的。

您可以使用 AFNetworking。如果你的回答是这样

{
  "my_response": {"name": "XXX","area": "XXX","num": "XXX"
  },
  "other_response": {"message": "Hello","status": "success","flag_value": "1"
  }
}

步骤 1 :- 并设置时间间隔。

- (void)yourMethod{
    NSString *urlString = [NSString stringWithFormat:@"%@", your_service_url];
    NSURL *url = [NSURL URLWithString:urlString];

   AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
   [AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/html"]];

   NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:

                           your_parameters_list,
                            nil];
        NSMutableURLRequest *jsonRequest = [httpClient requestWithMethod:@"POST"
                                                                path:urlString
                                                          parameters:params];

    [jsonRequest setTimeoutInterval:120];

    AFJSONRequestOperation *operation =
    [AFJSONRequestOperation JSONRequestOperationWithRequest:jsonRequest success: ^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        NSLog(@" Success %@", JSON);

        NSDictionary *jsonDictionary1 = [JSON valueForKey:@"my_response"];
        NSDictionary *jsonDictionary2 = [JSON valueForKey:@"other_response"];

                NSString* name = [jsonDictionary1 valueForKey:@“name”];
                NSString* area = [jsonDictionary1 valueForKey:@"name"];
                NSString* num =  [jsonDictionary1 valueForKey:@"num"];




    } failure: ^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        NSLog(@"Fail %@", [error userInfo]);

        NSLog(@“Error %@", [error localizedRecoverySuggestion]);


    }];

    [operation start];
}