Convert NSURLConnection to NSURLSessionUploadTask example

后端 未结 1 1395
孤街浪徒
孤街浪徒 2021-01-21 18:49

Hi everyone and thanks in advance for any help providing in understanding in how to convert some NSURLConnection code into the newer NSURLSession. What I am trying to do is to m

相关标签:
1条回答
  • 2021-01-21 19:43

    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);
    }
    
    0 讨论(0)
提交回复
热议问题