Nsurlsession implementing file Uploads

Source: Internet
Author: User

(1) How to implement file upload

      /*     第一个参数:请求对象     第二个参数:请求体(要上传的文件数据)     block回调:     NSData:响应体     NSURLResponse:响应头     NSError:请求的错误信息     */    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

/* 调用该方法上传文件数据 如果文件数据很大,那么该方法会被调用多次 参数说明:     totalBytesSent:已经上传的文件数据的大小     totalBytesExpectedToSend:文件的总大小 */-(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 作用:可以统一配置NSURLSession,如请求超时等02 创建的方式和使用
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 of 10 seconds Config.timeoutintervalforrequest = 10; //whether to continue the request (upload or download) in the case of a cellular network Config.allowscellularaccess = Span class= "Hljs-literal" >NO; _session = [nsurlsession sessionwithconfiguration:config delegate: self delegatequeue:[nsoperationqueue Mainqueue]]; } return _session;}           

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.