NSURLSession download and nsurlsession background download

Source: Internet
Author: User

NSURLSession download and nsurlsession background download

Ios7 introduces NSURLSession, which supports new network operations related to the background:

1. Background upload and download;

2. network operations can be paused and restored without using nsoperation and nsurlsession APIs.

3. As a configurable container: for example, you can set some attributes of the http header and save them in the session without repeated configuration.

4. sub-classes are supported and private sessions are supported.

5. Improved the authentication callback. Previously, the nsurlconnection authentication callback could not match the request. The callback may come from any request. Now, each request can be performed in the specified proxy method.

Next we will briefly study how to download:

:

Main Code:

1. Define several global variables

@interface ViewController (){    NSURLSessionDownloadTask * _task;    NSData * _data;    NSURLSession * _session;    NSURLRequest * _request;    UIProgressView * _pro;    UIImageView * _imageView;    }

2. Add an image progress bar to the view

_imageView=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 300, 300)];    _imageView.center=self.view.center;    [self.view addSubview:_imageView];    _pro=[[UIProgressView alloc] initWithFrame:CGRectMake(_imageView.frame.origin.x, _imageView.frame.origin.y+400, 300, 40)];

3. Add buttons to the view (add three buttons in the same way)

UIButton * button = [[UIButton alloc] initWithFrame: CGRectMake (50, _ imageView. frame. origin. y + 400 + 20, 50, 40)]; button. backgroundColor = [UIColor blueColor]; [button setTitle: @ "" forState: UIControlStateNormal]; [button addTarget: self action: @ selector (ddLoad) forControlEvents: UIControlEventTouchUpInside]; button. layer. borderWidth = 1; button. layer. borderColor = [UIColor blueColor]. CGColor; button. layer. cornerRadius = 5; [self. view addSubview: button];

4. Network status monitoring through AFNetworkReachabilityManager

-(Void) _ checkNet {// enable network status monitoring [[AFNetworkReachabilityManager sharedManager] startMonitoring]; [AFNetworkReachabilityManager sharedManager] running: ^ (AFNetworkReachabilityStatus status) {if (status = AFNetworkReachabilityStatusReachableViaWiFi) {NSLog (@ "current is wifi");} if (status = success) {NSLog (@ "current is 3G ");} if (status = AFNetworkReachabilityStatusNotReachable) {NSLog (@ "No network currently");} if (status = AFNetworkReachabilityStatusUnknown) {NSLog (@ "currently unknown network") ;}}] ;}

5. Start download

-(Void) ddLoad {NSURLSessionConfiguration * config = [NSURLSessionConfiguration defaultSessionConfiguration]; _ session = [NSURLSession sessionWithConfiguration: config delegate: self delegateQueue: nil]; // NSURL * url = [NSURL URLWithString: @ src]; _ request = [NSURLRequest requestWithURL: url]; _ task = [_ session downloadTaskWithRequest: _ request]; NSLog (@ "Start loading"); [_ task resume];}

6. Set pause and reply.

-(Void) pause {// pause NSLog (@ "pause download"); [_ task cancelByProducingResumeData: ^ (NSData * resumeData) {_ data = resumeData;}]; _ task = nil;}-(void) resume {// restore NSLog (@ "resume download"); if (! _ Data) {NSURL * url = [NSURL URLWithString: @ src]; _ request = [NSURLRequest requestWithURL: url]; _ task = [_ session downloadTaskWithRequest: _ request];} else {_ task = [_ session downloadTaskWithResumeData: _ data];} [_ task resume];}

7. The agent method is used to save the downloaded file and monitor the download progress.

# Pragma mark-delegate-(void) URLSession :( NSURLSession *) session downloadTask :( NSURLSessionDownloadTask *) downloadTask failed :( NSURL *) location {NSURL * url = [NSURL fileURLWithPath: @ "/Users/jredu/Desktop/tt.png"]; NSFileManager * manager = [NSFileManager defaultManager]; [manager moveItemAtURL: location toURL: url error: nil]; dispatch_async (dispatch_get_main_queue (), ^ {NSData * data = [manager contentsAtPath: @ "/Users/jredu/Desktop/tt.png"]; UIImage * image = [UIImage alloc] initWithData: data]; _ imageView. image = image; UIAlertView * alert = [[UIAlertView alloc] initWithTitle: nil message: @ "download completed" delegate: self cancelButtonTitle: @ "OK" otherButtonTitles: nil]; [alert show];});}-(void) URLSession :( NSURLSession *) session downloadTask :( bytes *) downloadTask didWriteData :( int64_t) bytesWritten minutes :( int64_t) interval :( int64_t) totalBytesExpectedToWrite {CGFloat progress = (totalBytesWritten * 1.0)/totalBytesExpectedToWrite; dispatch_async (dispatch_get_main_queue (), ^ {_ pro. progress = progress ;});}

 

Author: Jerry Education
Source: http://www.cnblogs.com/jerehedu/
Copyright Disclaimer: The copyright of this article is shared by Yantai jereh Education Technology Co., Ltd. and the blog Park. You are welcome to repost it. However, you must keep this statement without the consent of the author and provide the original article connection clearly on the article page, otherwise, you are entitled to pursue legal liability.
Technical Consultation:

Related Article

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.