NSURLSession需要太多时间

时间:2015-08-14 07:48:40

标签: objective-c nsurlsession nsoperationqueue

我使用NSURLSession发布请求。虽然我将队列设置为主队列仍然需要太多时间来响应

 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,但它只有一个答案与我正在做的相似。我缺少什么?

2 个答案:

答案 0 :(得分:1)

当您使用所需的代码更新问题时,我会在这里说什么,这使得您的请求变慢,因为这是网络请求的一些事情,它将取决于网络速度,服务器响应时间等不同的事情。在不同的网络设备上进行测试时是值得的。

答案 1 :(得分:0)

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

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

Stpe 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];
}