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

Asynchronous request timeout interval never stop

我有使用 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
        });

    }];

}

根据 Whosebug 上的另一个问题,POST 的默认超时是 240 秒,任何更短的间隔都将被忽略。

Link 回答 here