异步请求超时间隔永不停止

时间:2015-09-16 13:16:32

标签: objective-c asynchronous nsurlconnection nsurlrequest sendasynchronousrequest

我有异步请求通过POST将图像发送到服务器。我将timeoutInterval设置为10秒。如果它将图像发送到10秒,一切正常,但是当用户连接较差时,它应该在10秒后停止请求。但这个要求似乎从未停止过。你能帮忙吗?

- (void)postDataWithImage:(NSData *)imageData {

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@.%@",API_URL,self.method]]];
    [request setCachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
    [request setHTTPShouldHandleCookies:NO];
    [request setTimeoutInterval:10.0];
    [request setHTTPMethod:@"POST"];
    NSString *boundary = @"unique-consistent-string";

    // set Content-Type in HTTP header
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
    [request setValue:contentType forHTTPHeaderField: @"Content-Type"];

    // post body
    NSMutableData *body = [NSMutableData data];

    for (NSString *param in self.parametersDictionary) {
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=%@\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"%@\r\n", [self.parametersDictionary objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
    }

    // add image data
    if (imageData) {
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=%@; filename=place.jpg\r\n", @"i"] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:imageData];
        [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    }

    [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    // setting the body of the post to the reqeust
    [request setHTTPBody:body];

    // set the content-length
    NSString *postLength = [NSString stringWithFormat:@"%d", (int)[body length]];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^(void){

        NSLog(@"Response %@",response);

        if ([data length] > 0) {
            NSLog(@"Success");
        } else {
            NSLog(@"Error"); // This never show me
        });

    }];

}

1 个答案:

答案 0 :(得分:1)

根据Stackoverflow上的另一个问题,POST的默认超时为240秒,任何较短的间隔都会被忽略。

回复here

的链接