NSURLSession download and resumable data transfer, nsurlsession
NSURLSession is a new network interface after iOS7, which is similar to the common use of NSURLConnection. When the program is on the frontend, NSURLSession and NSURLConnection can replace each other. However, when you force close the program, the NSURLSession will be automatically disconnected by default. Compared with NSURLSession, the advantage of NSURLSession is mainly reflected in background operations, and it also provides better support for NSURLSession in the most popular framework AFNetworking.
The main functions are as follows:
1. download the file to the memory.
2. download the file to the path
3. Upload the specified file.
Case study: resumable upload of image downloads
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. Monitor the network status 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 ;});}