iOS Development Web Learning 12: nsurlsession Implementing file Uploads

Source: Internet
Author: User

#import "ViewController.h"//----WEBKITFORMBOUNDARYVMI3CAV0SGUTL8TR#defineKboundary @ "----webkitformboundaryjv0ufa04ed44ahwx"#defineknewline [@ "\ r \ n" datausingencoding:nsutf8stringencoding]@interfaceViewcontroller () <NSURLSessionDataDelegate>/** Notes*/@property (nonatomic, strong) Nsurlsession*session;@end@implementationViewcontroller-(Nsurlsession *) session{if(_session = =Nil) {nsurlsessionconfiguration*config =[Nsurlsessionconfiguration defaultsessionconfiguration]; //whether to run cellular accessConfig.allowscellularaccess =YES; Config.timeoutintervalforrequest= the; _session= [Nsurlsession sessionwithconfiguration:configDelegate: Self delegatequeue:[nsoperationqueue mainqueue]]; }    return_session;}-(void) Touchesbegan: (Nsset<uitouch *> *) touches withevent: (Uievent *)Event{[self upload2];}-(void) upload{//1.urlNsurl *url = [Nsurl urlwithstring:@"Http://120.25.226.186:32812/upload"]; //2. Create a Request objectNsmutableurlrequest *request =[Nsmutableurlrequest Requestwithurl:url]; //2.1 Setting the request methodRequest. HttpMethod =@"POST"; //2.2 Setting the request header information[Request Setvalue:[nsstring stringWithFormat:@"multipart/form-data; boundary=%@", Kboundary] Forhttpheaderfield:@"Content-type"]; //3. Creating a Session Object//nsurlsession *session = [Nsurlsession sharedsession]; //4. Create an upload task    /*first parameter: The second parameter of the Request object: Pass is the data to be uploaded (request body) The third parameter:*/Nsurlsessionuploadtask*uploadtask = [self.session uploadtaskwithrequest:request fromdata:[self Getbodydata] completionHandler:^ (NSData * _ Nullable data, Nsurlresponse * _nullable response, Nserror *_nullable Error) {              //6. ParsingNSLog (@"%@", [[NSString Alloc]initwithdata:data encoding:nsutf8stringencoding]);        }]; //5. Execute Task[Uploadtask resume];}-(void) upload2{//1.urlNsurl *url = [Nsurl urlwithstring:@"Http://120.25.226.186:32812/upload"]; //2. Create a Request objectNsmutableurlrequest *request =[Nsmutableurlrequest Requestwithurl:url]; //2.1 Setting the request methodRequest. HttpMethod =@"POST"; //2.2 Setting the request header information[Request Setvalue:[nsstring stringWithFormat:@"multipart/form-data; boundary=%@", Kboundary] Forhttpheaderfield:@"Content-type"]; //3. Creating a Session Object//4. Create an upload task    /*first parameter: Request object Second argument: Delivery is the data to be uploaded (request body)*/Nsurlsessionuploadtask*uploadtask = [self.session uploadtaskwithrequest:request fromdata:[self Getbodydata] completionHandler:^ (NSData * _ Nullable data, Nsurlresponse * _nullable response, Nserror *_nullable Error) {                //6. ParsingNSLog (@"%@", [[NSString Alloc]initwithdata:data encoding:nsutf8stringencoding]);        }]; //5. Execute Task[Uploadtask resume];}-(NSData *) getbodydata{Nsmutabledata*filedata =[Nsmutabledata data]; //5.1 File Parameters    /*--delimiter content-disposition:form-data; name= "file"; filename= "Snip20160225_341.png" content-type:image/pn G (MIMEType: Large type/small type) blank line file parameters*/[FileData appenddata:[[nsstring stringWithFormat:@"--%@", Kboundary] datausingencoding:nsutf8stringencoding]];        [FileData Appenddata:knewline]; //name:file Server-specified parameters//the name of the Filename:Snip20160225_341.png file saved to the server//content-type: type of File[FileData appenddata:[@"content-disposition:form-data; name=\"File\"; filename=\ "sss.png\""Datausingencoding:nsutf8stringencoding]];    [FileData Appenddata:knewline]; [FileData appenddata:[@"Content-type:image/png"Datausingencoding:nsutf8stringencoding]];    [FileData Appenddata:knewline];        [FileData Appenddata:knewline]; UIImage*image = [UIImage imagenamed:@"snip20160226_90"]; //UIImage--->nsdataNSData *imagedata =uiimagepngrepresentation (image);    [FileData Appenddata:imagedata];        [FileData Appenddata:knewline]; //5.2 Non-file parameters    /*--delimiter content-disposition:form-data; name= "username" Blank line 123456*/[FileData appenddata:[[nsstring stringWithFormat:@"--%@", Kboundary] datausingencoding:nsutf8stringencoding]];    [FileData Appenddata:knewline]; [FileData appenddata:[@"content-disposition:form-data; name=\"Username\""Datausingencoding:nsutf8stringencoding]];    [FileData Appenddata:knewline];    [FileData Appenddata:knewline]; [FileData appenddata:[@"123456"Datausingencoding:nsutf8stringencoding]];        [FileData Appenddata:knewline]; //5.3 End Identification    /*-- delimiter--*/[FileData appenddata:[[nsstring stringWithFormat:@"--%@--", Kboundary] datausingencoding:nsutf8stringencoding]]; returnFileData;}#pragmaMark----------------------#pragmaMark Nsurlsessiondatadelegate/** @param bytessent The data sent this time * @param the size of totalbytessent upload completed * @param Totalbytesexpectedt Total size of osend file*/-(void) Urlsession: (Nsurlsession *) session Task: (Nsurlsessiontask *) Task Didsendbodydata: (int64_t) bytessent totalbytessent: (int64_t) totalbytessent totalbytesexpectedtosend: ( int64_t) totalbytesexpectedtosend{NSLog (@"%f",1.0*totalbytessent/totalbytesexpectedtosend);}@end

# # # # # #7 nsurlsession implementation File upload

(1) How to implement file upload

"' OBJC

/*

First parameter: Request object

Second parameter: request body (file data to upload)

Block callback:

NSData: Response body

Nsurlresponse: Response Header

Nserror: The requested error message

*/

Nsurlsessionuploadtask *uploadtask = [Session uploadtaskwithrequest:request fromdata:data completionHandler:^ (NSData * __nullable data, Nsurlresponse * __nullable response, Nserror * __nullable error)

```

(2) Set up Agent to listen for file upload progress in Agent method

"' OBJC

/*

Call this method to upload file data

If the file data is large, then the method is called multiple times

Parameter description:

Totalbytessent: The size of the file data that has been uploaded

Totalbytesexpectedtosend: Total size of file

*/

-(void) Urlsession: (nonnull nsurlsession *) session task: (nonnull nsurlsessiontask *) Task Didsendbodydata: (int64_t) BytesSent totalbytessent: (int64_t) totalbytessent totalbytesexpectedtosend: (int64_t) TotalBytesExpectedToSend

{

NSLog (@ "%.2f", 1.0 * totalbytessent/totalbytesexpectedtosend);

}

```

(3) About nsurlsessionconfiguration related

01 functions: Nsurlsession can be configured uniformly, such as request timeout, etc.

02 Ways to create and use

"' OBJC

Three ways to create a configuration

+ (nsurlsessionconfiguration *) defaultsessionconfiguration;

+ (nsurlsessionconfiguration *) ephemeralsessionconfiguration;

+ (Nsurlsessionconfiguration *) Backgroundsessionconfigurationwithidentifier: (NSString *) identifier NS_AVAILABLE (10 _10, 8_0);

Unified Configuration Nsurlsession

-(Nsurlsession *) session

{

if (_session = = nil) {

Create Nsurlsessionconfiguration

Nsurlsessionconfiguration *config = [Nsurlsessionconfiguration defaultsessionconfiguration];

Set request Timeout to 10 seconds

Config.timeoutintervalforrequest = 10;

Whether to continue the request (upload or download) in the case of a cellular network

config.allowscellularaccess = NO;

_session = [nsurlsession sessionwithconfiguration:config delegate:self delegatequeue:[nsoperationqueue MainQueue]];

}

return _session;

}

```

iOS Development Web Learning 12: nsurlsession Implementing file Uploads

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.