使用 NSURLSession 时 NSMutableURLRequest 发送 2 次

NSMutableURLRequest sending 2 times while using NSURLSession

我正在使用 NSMutableURLRequest 在我使用

时工作正常
- (void)postAsynchronousOnQueue:(NSOperationQueue*)queue completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*))completionHandler {
    NSURLRequest* request = [self createPostRequest];
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:completionHandler];
}
-(NSURLRequest*)createPostRequest {
        NSMutableURLRequest* request = [[HttpRequest requestWithRelativePath:@"/photo"] toNSMutableURLRequest];
             [request setHTTPMethod:@"POST"];
             [request setHTTPBody:[self encodeParamsForUpload]];
             return request;  
}

但问题是当我的应用程序处于后台模式时它无法运行。

这是我的 HttpRequest class 方法:

+(id)requestWithRelativePath:(NSString*)docpath {
    return [[HttpRequest alloc] initWithRelativePath:docpath server:server username:email password:password];
}  
-(id)initWithRelativePath:(NSString*)docpath server:(NSString*)server username:(NSString*)username password:(NSString*)password {
    if (self = [super init]) {
        docpath = [docpath stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
        _request = [self createRequestWithDocPath:docpath server:server username:username password:password];
    }
    return self;
}

- (NSMutableURLRequest*)createRequestWithDocPath:(NSString*)docpath server:(NSString*)server username:(NSString*)username password:(NSString*)password {
    NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"https://%@%@", server, docpath]];
    NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url];
    [request setTimeoutInterval:120.0];
    if ((username != nil) && (password != nil)){
        NSString *authStr = [NSString stringWithFormat:@"%@:%@", username, password];
        NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
        NSString *authValue = [NSString stringWithFormat:@"Basic %@", [self base64Encoding:authData]];
        [request setValue:authValue forHTTPHeaderField:@"Authorization"];
    }
    return request;
}

从堆栈溢出我发现 NSURLSession 可以在后台工作 API 调用。所以我用了NSURLSession。这是我更新的代码:

- (void)postAsynchronousOnQueue:(NSOperationQueue*)queue completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*))completionHandler {
    NSURLRequest* request = [self createPostRequest];
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:completionHandler];
}
-(NSURLRequest*)createPostRequest {
    NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration ephemeralSessionConfiguration];
    NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];

    NSMutableURLRequest* request = [[HttpRequest requestWithRelativePath:@"/photo"] toNSMutableURLRequest];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:[self encodeParamsForUpload]];
    //Create task
    NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        //Handle your response here
        [[NSURLSession sharedSession]invalidateAndCancel];
    }];

    [dataTask resume];
    return request; 
}

但是,当我使用 NSURLSession 时,请求发送了两次,我已经将断点放在 NSMutableURLRequest 行中,但它只调用了一次。

请帮我解决问题。

您的 createPostRequest 正在创建请求并通过 NSURLSession 提交。但它也 returns NSURLRequestpostAsynchronousOnQueue 继续提交它,这次是通过已弃用的 NSURLConnection

删除 NSURLConnection 代码,仅依靠 NSURLSession 发出请求。


例如:

- (void)postAsynchronousOnQueue:(NSOperationQueue*)queue completionHandler:(void (^)(NSData *, NSURLResponse*, NSError*))completionHandler {
    NSURLSession *defaultSession = [NSURLSession sharedSession];

    NSMutableURLRequest* request = [[HttpRequest requestWithRelativePath:@"/photo"] toNSMutableURLRequest];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:[self encodeParamsForUpload]];

    NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        //Handle your response here
        [queue addOperationWithBlock:^{
            completionHandler(data, response, error);
        }];
    }];

    [dataTask resume]; 
}