Network Programming for iOS development-5. NSURLSessionUploadTask + NSURLSessionDataDelegate proxy upload, nsurlsessiondelegate

Source: Internet
Author: User

Network Programming for iOS development-5. NSURLSessionUploadTask + NSURLSessionDataDelegate proxy upload, nsurlsessiondelegate

The main content of NSURLSession is coming to an end. Here we will talk about file upload. Of course, NSURLSessionUploadTask is required for file upload. Here we will directly explain how to use NSURLSessionDataDelegate together with the proxy to implement the file upload function. In addition, the idea of uploading files is the same as that mentioned in my previous article "network programming for iOS development -- using NSURLConnection to upload files" in NSURLConnection, are to splice the request information, and then pass it into the request for upload. This splicing process is necessary, but it is also complicated. I will not be able to explain the details here. In addition, the use of proxy is relatively simple, so all source code is displayed directly.

 

1 # import "ViewController. h "2 # define kBoundary @" ---- WebKitFormBoundary0IQAt0HA7oxwIx3f "3 # define KNewLine [@" \ r \ n "dataUsingEncoding: NSUTF8StringEncoding] 5 @ interface ViewController () <NSURLSessionDataDelegate> 6 7 @ end 8 9 @ implementation ViewController 10 11-(void) touchesBegan :( NSSet <UITouch *> *) touches withEvent :( ui* event *) event 12 {13 NSLog (@ "------"); 14 // 1. create a session object and set the proxy 15 NSURLSession * session = [NSURLSession sessionWithConfiguration: [NSURLSessionConfiguration defaultSessionConfiguration] delegate: self delegateQueue: [NSOperationQueue mainQueue]; 16 17 // 2. create a request object 18 NSURL * url = [NSURL URLWithString: @ "http: // 120.25.226.186: 32812/upload"]; 19 NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL: url]; 20 21 // 2.1 modify the request Method 22 request. HTTPMethod = @ "POST"; 23 24 // 2.2 Set Request header 25 NSString * header = [NSString stringWithFormat: @ "multipart/form-data; boundary = % @", kBoundary]; 26 [request setValue: header forHTTPHeaderField: @ "Content-Type"]; 27 28 // 3. create upload task 29/* 30 first parameter: request object 31 second parameter: parameters of the file to be uploaded (binary data 32 third parameter: completionHandler 33 data: response body information returned by the server 34 response: response Header 35 */36 NSURLSessionUploadTask * uploadTask = [session uploadTaskWithRequest: request fromData: [self getBodyData] completionHandler: ^ (NSData * _ Nullable data, NSURLResponse * _ Nullable response, NSError * _ Nullable error) {37 38 // 5. parsing result 39 NSLog (@ "% @", [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]); 40}]; 41 42 // 4. execute task 43 [uploadTask resume]; 44 45} 46 47-(NSData *) getBodyData 48 {49 // 5. splicing data 50 NSMutableData * fileData = [NSMutableData data]; 51 52 // 5.1 merging file parameter 53/* 54 -- separator 55 Content-Disposition: form-data; name = "file"; filename = "Snip20151228_572.png" 56 Content-Type: image/png 57 empty line 58 file binary data 59 */60 [fileData appendData: [[NSString stringWithFormat: @ "-- % @", kBoundary] dataUsingEncoding: NSUTF8StringEncoding]; 61 [fileData appendData: KNewLine]; 62 // name = "file": parameter, is a fixed 63 // filename: the name of the file to be uploaded to the server for storage. For example, 64 [fileData appendData: [@ "Content-Disposition: form-data; name = \ "file \"; filename = \ "Snip20151228_572.png \" "dataUsingEncoding: NSUTF8StringEncoding]; 65 66 [fileData appendData: KNewLine]; 67 // Content-Type: type of the file to be uploaded (MIMEType) 68 [fileData appendData: [@ "Content-Type: image/png" dataUsingEncoding: NSUTF8StringEncoding]; 69 [fileData appendData: KNewLine]; 70 [fileData appendData: KNewLine]; 71 72 UIImage * image = [UIImage imageNamed: @ "Snip20151229_713"]; 73 NSData * imageData = UIImagePNGRepresentation (image); 74 [fileData appendData: imageData]; 75 [fileData appendData: KNewLine]; 76 77 // 5.2 splicing non-file parameter 78/* 79 -- separator 80 Content-Disposition: form-data; name = "username" 81 empty line 82 binary data of non-file parameters 83 */84 [fileData appendData: [[NSString stringWithFormat: @ "-- % @", kBoundary] dataUsingEncoding: NSUTF8StringEncoding]; 85 [fileData appendData: KNewLine]; 86 87 // username: Same as file: Server regulations 88 [fileData appendData: [@ "Content-Disposition: form-data; name = \ "username \" "dataUsingEncoding: NSUTF8StringEncoding]; 89 [fileData appendData: KNewLine]; 90 [fileData appendData: KNewLine]; 91 [fileData appendData: [@ "dashen9" dataUsingEncoding: NSUTF8StringEncoding]; 92 [fileData appendData: KNewLine]; 93 94 // 5.3 end of the splicing mark 95/* 96 -- delimiter -- 97 */98 [fileData appendData: [[NSString stringWithFormat: @ "-- % @ --", kBoundary] dataUsingEncoding: NSUTF8StringEncoding]; 99 100 return fileData; 101} 102 103 # pragma mark -------------------- 104 # pragma mark failed/* 106 first parameter: bytesSent the size of the data sent this time is 107 Second parameter: total data sent by totalBytesSent 108 third parameter: total size of the hosts file 109 */110-(void) URLSession :( NSURLSession *) session task :( NSURLSessionTask *) task didSendBodyData :( int64_t) bytesSent totalBytesSent :( int64_t) totalBytesSent upload :( int64_t) bytes {112 NSLog (@ "% f data uploaded", 1.0 * totalBytesSent/bytes); 113} 114 @ end

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.