你好,歡迎來到IOS教程網

 Ios教程網 >> IOS使用技巧 >> IOS技巧綜合 >> iOS NSURLSession的使用

iOS NSURLSession的使用

編輯:IOS技巧綜合
[摘要]本文是對iOS NSURLSession的使用的講解,對學習IOS蘋果軟件開發有所幫助,與大家分享。

1.NSURLSessionDataTask

     // 確定URL
     NSString *urlStr = @"http://localhost/試試看";
     urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
     NSURL *url = [NSURL URLWithString:urlStr];
     
     // 確定request
     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:2.0f];
     
     // 確定會話
     NSURLSession *session = [NSURLSession sharedSession];
     
     // 由會話生成任務
     NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
         NSLog(@"response-- %@",response);
         NSLog(@"data--%@",data);
         
         // 刷新UI,一定要返回主線程去刷新
         dispatch_async(dispatch_get_main_queue(), ^{
             [self.imageView  setImage:[UIImage imageWithData:data]];
         });
 
     }];
     
     [dataTask resume];

2.NSURLSessionDownloadTask實現簡單的下載功能

     // 確定URL
     NSString *urlStr = @"http://localhost/試試看";
     urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
     NSURL *url = [NSURL URLWithString:urlStr];
     
     // 確定request
     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:2.0f];
     
     // 確定會話
     NSURLSession *session = [NSURLSession sharedSession];
     
     // 由會話生成任務
     NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
         // 從tmp中拷貝文件到cache
         NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
         NSURL *cachePathURL = [NSURL fileURLWithPath:cachePath];
         NSString *fileNameByMD5 = [[[response URL] absoluteString] MD5];
         NSURL *fileURL = [cachePathURL URLByAppendingPathComponent: fileNameByMD5];
 
         NSFileManager *mgr = [NSFileManager defaultManager];
         [mgr moveItemAtURL:location toURL:fileURL  error:NULL];
         
     }];
     
     [downloadTask resume];
 - (NSString *)MD5
 {
     const char *cStr = [self UTF8String];
     unsigned char digest[CC_MD5_DIGEST_LENGTH];
 
     CC_MD5(cStr, strlen(cStr), digest);
 
     NSMutableString *result = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
 
     for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
         [result appendFormat:@"%02x", digest[i]];
     }
 
     return result;
 }

3.NSURLSessionDownloadTask實現復雜的下載功能:斷點續傳\後台下載

http://blog.csdn.net/majiakun1/article/details/38133789

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved