Resumable upload for ios: NSURLSession and NSURLSessionDataTask are implemented,

Source: Internet
Author: User

Resumable upload for ios: NSURLSession and NSURLSessionDataTask are implemented,

Although the NSURLSessionDownloadTask provided by Apple can implement resumable data transfer, it cannot be processed in some cases, for example, the program is forcibly exited or not called.

The cancelByProducingResumeData method cannot be resumed.

 

The process of resumable Data Transfer Using NSURLSession and nsurlsessionask ask is as follows:

1. Configure the Range request header field of the NSMutableURLRequest object

2. Create an NSURLSession object using the proxy

3. Use the NSURLSession object and the NSMutableURLRequest object to create the NSURLSessionDataTask object and start the task.

4. append the downloaded data to the target file in the didReceiveData method of NSURLSessionDataDelegate.

 

The following is a specific implementation that encapsulates a resume manager. Can be directly copied to your project, you can also refer to the demo I provide: http://pan.baidu.com/s/1c0BHToW

 

//// MQLResumeManager. h /// Created by MQL on 15/10/21. // Copyright©2015. all rights reserved. // # import <Foundation/Foundation. h> @ interface MQLResumeManager: NSObject/*** creates a resumable upload management object, start the download request ** @ param url File resource address * @ param targetPath file storage path * @ param success File Download success callback block * @ param failure file download failure callback block *@ callback block for param progress File Download progress ** @ return resumable upload management object **/+ (MQLResumeManager *) resumeManagerWithURL :( NSURL *) url targetPath :( NSString *) targetPath success :( void (^) () success failure :( void (^) (NSError * error )) failure progress :( void (^) (longlongtotalReceivedContentLength, longlong totalContentLength) progress;/*** start the resumable download Request */-(void) start; /*** cancel the resumable download Request */-(void) cancel; @ end

 

 

 

1 // 2 3 // MQLResumeManager. m 4 5 // 6 7 // Created by MQL on 15/10/21. 8 9 // Copyright©2015. all rights reserved. 10 11 // 12 13 14 15 # import "MQLResumeManager. h "16 17 18 19 typedef void (^ completionBlock) (); 20 21 typedef void (^ progressBlock) (); 22 23 24 25 @ interface MQLResumeManager () <NSURLSessionDelegate, NSURLSessionTaskDelegate> 26 27 28 29 @ property (nonatomic, strong) NSURLSession * session; // note that a session can only have one request task of 30 31 @ property (nonatomic, readwrite, retain) NSError * error; // please 32 33 @ property (nonatomic, readwrite, copy) completionBlockcompletionBlock; 34 35 @ property (nonatomic, readwrite, copy) progressBlock; 36 37 38 39 @ property (nonatomic, strong) NSURL * url; // file resource address: 40 41 @ property (nonatomic, strong) NSString * targetPath; // file storage path: 42 43 @ property longlong totalContentLength; // total file size 44 45 @ property longlong totalReceivedContentLength; // downloaded size 46 47 48 49 /* * 50 51 * callback block 52 53*54 55 * @ param success callback block 56 57 * @ param failure callback block 58 59 */60 61-(void) setCompletionBlockWithSuccess :( void (^) () success 62 63 failure :( void (^) (NSError * error) failure; 64 65 66 67/** 68 69 * set progress callback block 70 71*72 73 * @ param progress 74 75 */76 77-(void) setProgressBlockWithProgress :( void (^) (longlongtotalReceivedContentLength, longlong totalCo NtentLength) progress; 78 79 80 81/** 82 83 * Get File Size 84 85 * @ param path file path 86 87 * @ return file size 88 89*90 91 */92 93-(long long) fileSizeForPath :( NSString *) path; 94 95 96 97 @ end 98 99 100 101 @ implementation MQLResumeManager102 103 104 105/** 106 107 * callback block108 109*110 111 * @ param success callback block112 113 * @ param failure callback block114 115 */116 117-(void) setCompletionBlockWit HSuccess :( void (^) () success118 119 failure :( void (^) (NSError * error) failure {120 121 122 123 _ weak typeof (self) weakSelf = self; 124 125 self. completionBlock = ^ {126 127 128 129 dispatch_async (dispatch_get_main_queue (), ^ {130 131 132 133 if (weakSelf. error) {134 135 if (failure) {136 137 failure (weakSelf. error); 138 139} 140 141} else {142 143 if (success) {144 145 success (); 146 147} 148} 149 151 152 153}); 154 155 }; 156 157} 158 159 160 161/** 162 163 * set progress callback block164 165*166 167 * @ param progress168 169 */170 171-(void) setProgressBlockWithProgress :( void (^) (longlongtotalReceivedContentLength, longlong totalContentLength) SS {172 173 174 _ weak typeof (self) weakSelf = self; 175 176 177 self. progressBlock = ^ {178 179 180 181 dispatch_async (dispatch_get_main_queue (), ^ {182 183 184 1 85 progress (weakSelf. totalReceivedContentLength, weakSelf. totalContentLength); 186 187}); 188 189 }; 190 191} 192 193 194 195/** 196 197 * Get File Size 198 199 * @ param path file path 200 201 * @ return file size 202 203*204 205 */206 207 -(long) fileSizeForPath :( NSString *) path {208 209 210 211 long fileSize = 0; 212 213 NSFileManager * fileManager = [NSFileManagernew]; // not thread safe214 215 if ([fileManage R fileExistsAtPath: path]) {216 217 NSError * error = nil; 218 219 NSDictionary * fileDict = [fileManagerattributesOfItemAtPath: path error: & error]; 220 221 if (! Error & fileDict) {222 223 fileSize = [fileDict fileSize]; 224 225} 226 227 228 return fileSize; 230 231} 232 233 234 235/** 236 237 * Create a resumable upload management object, start the download request 238 239*240 241 * @ param url File resource address 242 243 * @ param targetPath file storage path 244 245 * @ param success callback block 246 247 *@ callback block 248 249 * @ param progress callback block 250 251 * @ return resumable upload management object 252 253*254 255 */ 258 259 + (MQLRe SumeManager *) warn :( NSURL *) url260 261 targetPath :( NSString *) targetPath262 263 success :( void (^) () success264 265 failure :( void (^) (NSError * error )) failure266 267 progress :( void (^) (longlongtotalReceivedContentLength, longlong totalContentLength) progress {268 269 270 271 MQLResumeManager * manager = [[callback] init]; 272 273 274 275 manager. url = url; 276 277 manager.tar getPa Th = targetPath; 278 279 [managersetCompletionBlockWithSuccess: successfailure: failure]; 280 281 282 [manager setProgressBlockWithProgress: progress]; 283 284 285 manager. totalContentLength = 0; 286 287 manager. totalReceivedContentLength = 0; 288 289 290 291 return manager; 292 293} 294 295 296 297/** 298 299 * Start resumable download request 300 301 */302 303-(void) start {304 305 306 307 NSMutableURLRequest * request = [NSMutab LeURLRequestalloc] initWithURL: self. url]; 308 309 310 311 longlong downloadedBytes = self. totalReceivedContentLength = [selffileSizeForPath: self.tar getPath]; 312 313 if (downloadedBytes> 0) {314 315 316 317 NSString * requestRange = [NSStringstringWithFormat: @ "bytes = % llu -", downloadedBytes]; 318 319 [request setValue: requestRangeforHTTPHeaderField: @ "Range"]; 320 321} else {322 323 324 325 int fileDescrip Tor login open({self.tar getPathUTF8String], O_CREAT | O_EXCL | O_RDWR, 0666); 326 327 328 if (fileDescriptor> 0) {329 close (fileDescriptor ); 330 331} 332 333 334 335 336 337 NSURLSessionConfiguration * sessionConfiguration = [nsurlsessionconfigurationdefasessessionconfiguration]; 338 339 340 NSOperationQueue * queue = [[NSOperationQueuealloc] init]; 341 self. session = [NSURLSessionsessionWithConfiguration: sessi OnConfigurationdelegate: selfdelegateQueue: queue]; 342 343 344 345 NSURLSessionDataTask * dataTask = [self. sessiondataTaskWithRequest: request]; 346 347 [dataTask resume]; 348 349} 350 351 352 353/** 354 355 * cancel resumable download request 356 357 */358 359-(void) cancel {360 361 362 363 if (self. session) {364 365 366 367 [self. sessioninvalidateAndCancel]; 368 369 self. session = nil; 370 371} 372 373} 374 375 376 # pragma m Ark -- NSURLSessionDelegate378 379/* The last message a session delegate es. A session will only become380 381 * invalid because of a systemic error or when it has been382 383 * explicitly invalidated, in which case the error parameter will be nil.384 385 */386 387-(void) URLSession :( NSURLSession *) session failed :( nullableNSError *) error {388 389 390 NSLog (@ "didBecome InvalidWithError "); 392 393 394} 395 396 397 # pragma mark -- NSURLSessionTaskDelegate398 399/* Sent as the last message related to a specific task. error may be400 401 * nil, which implies that no error occurred and this task is complete.402 403 */404 405-(void) URLSession :( NSURLSession *) session task :( NSURLSessionTask *) task406 407 didCompleteWithError :( nullable NSError *) error {408 409 410 NS Log (@ "didCompleteWithError"); 412 413 414 415 if (error = nil & self. error = nil) {416 417 418 419 self. completionBlock (); 420 421 422 423} else if (error! = Nil) {424 425 426 427 if (error. code! =-999) {428 429 430 431 self. error = error; 432 433 self. completionBlock (); 434 435} 436 437 438 439} else if (self. error! = Nil) {440 441 442 443 self. completionBlock (); 444 445} 446 447 448 449 450} 451 452 453 454 # pragma mark -- NSURLSessionDataDelegate456 455/* Sent when data is available for the delegate to consume. it is458 459 * assumed that the delegate will retain and not copy the data. as460 461 * the data may be discontiguous, you shoshould use462 463 * [NSData enumerateByteRangesUsingBlock:] to access it.464 465 */466 467-(void) URLSession :( NSURLSession *) session dataTask :( NSURLSessionDataTask *) dataTask468 469 didReceiveData :( NSData *) data {470 471 472 473 // depending on the status code, 474 NSHTTPURLResponse * response = (NSHTTPURLResponse *) dataTask. response; 476 477 if (response. statusCode = 200) {478 479 480 481 self. totalContentLength = dataTask. countOfBytesExpectedToReceive; 482 483 484} else if (response. statusCode = 206) {486 487 488 NSString * contentRange = [response. allHeaderFieldsvalueForKey: @ "Content-Range"]; 490 491 if ([contentRange hasPrefix: @ "bytes"]) {492 493 NSArray * bytes = [contentRangecomponentsSeparatedByCharactersInSet: [Encoding: @ "-/"]; 494 495 if ([bytes count] = 4) {496 497 self. totalContentLength = [[bytesobjectAtIndex: 3] longLongValue]; 498 499} 500 501} 502 503} else if (response. statusCode = 416) {504 505 506 NSString * contentRange = [response. allHeaderFieldsvalueForKey: @ "Content-Range"]; 508 509 if ([contentRange hasPrefix: @ "bytes"]) {510 511 NSArray * bytes = [contentRangecomponentsSeparatedByCharactersInSet: [Encoding: @ "-/"]; 512 513 if ([bytes count] = 3) {514 515 516 517 self. totalContentLength = [[bytesobjectAtIndex: 2] longLongValue]; 518 519 if (self. totalReceivedContentLength = self. totalContentLength) {520 521 522 523 524 // indicates the update progress is 525 526 527 528 529. progressBlock (); 530 531} else {532 533 534 535 // 416 Requested Range Not Satisfiable536 537 self. error = [[NSErroralloc] initWithDomain: [self. urlabsoluteString] code: 416 userInfo: response. allHeaderFields]; 538 539} 540 541 542} 543 544 return; 545 546} else {547 548 549 550 551 // no other situations have found 552 553 return; 554 555} 556 557 558 559 // append data to the file 560 561 NSFileHandle * fileHandle = [NSFileHandlefileHandleForUpdatingAtPath: self.tar getPath]; 562 563 [fileHandle seekToEndOfFile]; // jump the node to the end of the file 564 565 566 567 [fileHandle writeData: data]; // append the data to 568 569 [fileHandle closeFile]; 570 571 572 573 // Update Progress 574 575 self. totalReceivedContentLength + = data. length; 576 577 self. progressBlock (); 578 579} 580 581 582 583 584 @ end

 

 

 

 

 

After verification, if the app can run in the background, datatask supports background transmission.
It is very easy to make your app run in the background:


# Import "AppDelegate. h"
Static UIBackgroundTaskIdentifier bgTask;


@ Interface AppDelegate ()


@ End


@ Implementation AppDelegate


-(BOOL) application :( UIApplication *) application didfinishlaunchingwitexceptions :( NSDictionary *) launchOptions {
// Override point for customization after application launch.
Return YES;
}


-(Void) applicationDidEnterBackground :( UIApplication *) application {

[Self getBackgroundTask];
}


-(Void) applicationWillEnterForeground :( UIApplication *) application {

[Self endBackgroundTask];
}


/**
* Obtain background tasks
*/
-(Void) getBackgroundTask {

NSLog (@ "getBackgroundTask ");
UIBackgroundTaskIdentifier tempTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler: ^ {

}];

If (bgTask! = UIBackgroundTaskInvalid ){

[Self endBackgroundTask];
}

BgTask = tempTask;

[Self defined mselector: @ selector (getBackgroundTask) withObject: nil afterDelay: 120];
}


/**
* End background tasks
*/
-(Void) endBackgroundTask {

[[UIApplication sharedApplication] endBackgroundTask: bgTask];
BgTask = UIBackgroundTaskInvalid;
}


@ End

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.