Difference between loading a multi-page form and NSURLSession.uploadTaskWithRequest

Based on the world of web programming, I really enjoy working with multi-page form requests for uploading files. However, on iOS, we have a thing called NSURLSessionusing a method uploadTaskWithRequest, which appears to be a call method to download images and the like.

Can you explain the difference between the two approaches, adding a multi-file form vs uploadTaskWithRequest? If I already have a backend that handles multi-line downloads, what settings might I need to support it uploadTaskWithRequest?

+4
source share
3 answers

uploadTaskWithRequest NSData, . . , .

, -, multipart/form-data, ( - AFNetworking Alamofire, ). , , dataTaskWithRequest ( HTTPBody NSMutableURLRequest) uploadTaskWithRequest ( HTTPBody, uploadTaskWithRequest).

, , Charles, , , .

+10

multipart/form-data

multipart/form-data Content-type RFC 1867, World Wide Web, HTML 4.0, HTML HTTP . , โ€‹โ€‹ . -.

multipart/form-data , , HTML. - -. , , RFC 7578 ( IETF).

, , , multipart/form-data / . . , / RFC - - , , , . - , .

NSURLSession uploadTaskWithRequest

NSURLSession . , , multipart/form-data.

NSURLSession POST NSURLRequest, . (, text/plain; charset=utf-8) . NSURLSession (, NSData). , , "" POST. - .

, uploadTaskWithRequest, , POST "" . , " " multipart/form-data, , URL- , ().

+2

, POST- multipart/form-data , , .

NSMutableURLRequest , (., , POST multipart/form-data Objective-C).

Then write the request body to a file and pass it to the uploadTaskWithRequest method for the NSURLSession that you created with backgroundSessionConfiguration:

NSString *filePath = [[NSSearchPathForDirectoriesInDomains(
                           NSCachesDirectory, NSUserDomainMask, YES) lastObject] 
                           stringByAppendingPathComponent:imageUUID];

[request.HTTPBody writeToFile:filePath atomically:YES];

NSURLSessionUploadTask *task = [urlSession uploadTaskWithRequest:request 
                                           fromFile:[NSURL fileURLWithPath:filePath]];
[task resume];

If you have several tasks and you want to distinguish them in the delegate callback, you can set the parameter (after you created the request) using the NSURLProtocol class:

[NSURLProtocol setProperty:imageUUID
                    forKey:@"yourKeyForTheImageUUID" 
                 inRequest:request];

and return it to a callback like this:

- (void)URLSession:(NSURLSession *)session
        task:(nonnull NSURLSessionTask *)task
        didCompleteWithError:(nullable NSError *)error
{
    NSString *imageUUID = [NSURLProtocol propertyForKey:@"yourKeyForTheImageUUID"
                                              inRequest:task.originalRequest];
0
source

Source: https://habr.com/ru/post/1611548/


All Articles