Convert NSURLConnection to NSURLSessionUploadTask example

北战南征 提交于 2019-12-02 01:36:01

I'm using a simple HTTPClient class I wrote, but unfortunately it currently does not support upload tasks. But below I propose a method for creating such an upload task. My client maintains a reference to an NSURLSession and a dictionary of running tasks (key is the task itself, value is the NSData received) as a way of asynchronously handling reception of response data for (possibly more than one) session tasks. In order to work my client implements the following protocols: . I would create the upload task as follows:

- (NSURLSessionTask *) startUploadTaskForURL: (NSURL *) url withData: (NSData *) data {
  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
  [request setHTTPMethod:@"POST"];
  [request addValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
  NSURLSessionUploadTask uploadTask = [self.session uploadTaskWithRequest:request fromData:data];
  [self scheduleTask:task];
  return task;
}

- (void) scheduleTask: (NSURLSessionTask *) task {
    [self.runningTasks setObject:[NSMutableData data] forKey:task];
    [task resume];
}

- (NSMutableData *) dataForTask: (NSURLSessionTask *) task {
    return [self.runningTasks objectForKey:task];
}

- (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
    NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"HTTPClient: Data task received data: %@", dataString);
    NSMutableData *runningData = [self dataForTask:dataTask];
    if (!runningData) {
        NSLog(@"No data found for task");
    }
    [runningData appendData: data];
}

- (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
    NSLog(@"HTTPClient: Task completed with error: %@", error);
    // my client also works with a delegate, so as to make it reusable
    [self.delegate sessionTask:task completedWithError:error data:[self dataForTask:task]];
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend {
    NSLog(@"HTTPClient: did send body data: %lld of %lld bytes ", totalBytesSent, totalBytesExpectedToSend);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!