够学一周的干货:多种方式实现文件下载功能

移动开发
这篇文章主要包括以下内容:(1)使用 NSURLConnection 直接方式(2)使用 NSURLConnection 代理方式(3)使用 NSURLSession 直接方式(4)使用 NSURLSession 代理方式(5)使用 AFNetworking 方式

[[151719]]

这篇文章主要包括以下内容:

(1)使用 NSURLConnection 直接方式

(2)使用 NSURLConnection 代理方式

(3)使用 NSURLSession 直接方式

(4)使用 NSURLSession 代理方式

(5)使用 AFNetworking 方式

附加功能:

(1)使用 AFNetworking 中的 AFNetworkReachabilityManager 来检查网络情况:

  • AFNetworkReachabilityStatusReachableViaWiFi:Wi-Fi 网络下

  • AFNetworkReachabilityStatusReachableViaWWAN:2G/3G/4G 蜂窝移动网络下

  • AFNetworkReachabilityStatusNotReachable:未连接网络

(2)使用 AFNetworking 中的 AFNetworkActivityIndicatorManager 来启动网络活动指示器:

  1. #import "AFNetworkActivityIndicatorManager.h" 
  2. //启动网络活动指示器;会根据网络交互情况,实时显示或隐藏网络活动指示器;他通过「通知与消息机制」来实现 [UIApplication sharedApplication].networkActivityIndicatorVisible 的控制 
  3. [AFNetworkActivityIndicatorManager sharedManager].enabled = YES; 

效果如下:

1.gif

blob.png

blob.png

blob.png

ViewController.h

 
  1. #import @interface ViewController : UITableViewController 
  2. @property (copy, nonatomic) NSArray *arrSampleName; 
  3.   
  4. - (instancetype)initWithSampleNameArray:(NSArray *)arrSampleName; 
  5.   
  6. @end 

ViewController.m

 
  1. #import "ViewController.h" 
  2. #import "NSURLConnectionViewController.h" 
  3. #import "NSURLConnectionDelegateViewController.h" 
  4. #import "NSURLSessionViewController.h" 
  5. #import "NSURLSessionDelegateViewController.h" 
  6. #import "AFNetworkingViewController.h" 
  7.   
  8. @interface ViewController () 
  9. - (void)layoutUI; 
  10. @end 
  11.   
  12. @implementation ViewController 
  13. - (void)viewDidLoad { 
  14.     [super viewDidLoad]; 
  15.       
  16.     [self layoutUI]; 
  17.   
  18. - (void)didReceiveMemoryWarning { 
  19.     [super didReceiveMemoryWarning]; 
  20.     // Dispose of any resources that can be recreated. 
  21.   
  22. - (instancetype)initWithSampleNameArray:(NSArray *)arrSampleName { 
  23.     if (self = [super initWithStyle:UITableViewStyleGrouped]) { 
  24.         self.navigationItem.title = @"多种方式实现文件下载功能"
  25.         self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:nil action:nil]; 
  26.           
  27.         _arrSampleName = arrSampleName; 
  28.     } 
  29.     return self; 
  30.   
  31. - (void)layoutUI { 
  32.   
  33. #pragma mark - UITableViewController相关方法重写 
  34. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section { 
  35.     return 0.1
  36.   
  37. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
  38.     return 1
  39.   
  40. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
  41.     return [_arrSampleName count]; 
  42.   
  43. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
  44.     static NSString *cellIdentifier = @"cell"
  45.     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 
  46.     if (!cell) { 
  47.         cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; 
  48.     } 
  49.     cell.textLabel.text = _arrSampleName[indexPath.row]; 
  50.     return cell; 
  51.   
  52. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
  53.     switch (indexPath.row) { 
  54.         case 0: { 
  55.             NSURLConnectionViewController *connectionVC = [NSURLConnectionViewController new]; 
  56.             [self.navigationController pushViewController:connectionVC animated:YES]; 
  57.             break
  58.         } 
  59.         case 1: { 
  60.             NSURLConnectionDelegateViewController *connectionDelegateVC = [NSURLConnectionDelegateViewController new]; 
  61.             [self.navigationController pushViewController:connectionDelegateVC animated:YES]; 
  62.             break
  63.         } 
  64.         case 2: { 
  65.             NSURLSessionViewController *sessionVC = [NSURLSessionViewController new]; 
  66.             [self.navigationController pushViewController:sessionVC animated:YES]; 
  67.             break
  68.         } 
  69.         case 3: { 
  70.             NSURLSessionDelegateViewController *sessionDelegateVC = [NSURLSessionDelegateViewController new]; 
  71.             [self.navigationController pushViewController:sessionDelegateVC animated:YES]; 
  72.             break
  73.         } 
  74.         case 4: { 
  75.             AFNetworkingViewController *networkingVC = [AFNetworkingViewController new]; 
  76.             [self.navigationController pushViewController:networkingVC animated:YES]; 
  77.             break
  78.         } 
  79.         default
  80.             break
  81.     } 
  82.   
  83. @end 

PrefixHeader.pch

 
  1. #define kFileURLStr @"http://files.cnblogs.com/files/huangjianwu/metro_demo使用Highcharts实现图表展示.zip" 
  2.   
  3. #define kTitleOfNSURLConnection @"使用 NSURLConnection 直接方式" 
  4. #define kTitleOfNSURLConnectionDelegate @"使用 NSURLConnection 代理方式" 
  5. #define kTitleOfNSURLSession @"使用 NSURLSession 直接方式" 
  6. #define kTitleOfNSURLSessionDelegate @"使用 NSURLSession 代理方式" 
  7. #define kTitleOfAFNetworking @"使用 AFNetworking 方式" 
  8.   
  9. #define kApplication [UIApplication sharedApplication] 

UIButton+BeautifulButton.h

 
  1. #import @interface UIButton (BeautifulButton) 
  2. /** 
  3.  *  根据按钮文字颜色,返回对应文字颜色的圆角按钮 
  4.  * 
  5.  *  @param tintColor 按钮文字颜色;nil 的话就为深灰色 
  6.  */ 
  7. - (void)beautifulButton:(UIColor *)tintColor; 
  8.   
  9. @end 

UIButton+BeautifulButton.m

 
  1. #import "UIButton+BeautifulButton.h" 
  2.   
  3. @implementation UIButton (BeautifulButton) 
  4.   
  5. - (void)beautifulButton:(UIColor *)tintColor { 
  6.     self.tintColor = tintColor ?: [UIColor darkGrayColor]; 
  7.     self.layer.masksToBounds = YES; 
  8.     self.layer.cornerRadius = 10.0
  9.     self.layer.borderColor = [UIColor grayColor].CGColor; 
  10.     self.layer.borderWidth = 1.0
  11.   
  12. @end 

NSURLConnectionViewController.h

 
  1. #import @interface NSURLConnectionViewController : UIViewController 
  2. @property (strong, nonatomic) IBOutlet UILabel *lblFileName; 
  3. @property (strong, nonatomic) IBOutlet UILabel *lblMessage; 
  4. @property (strong, nonatomic) IBOutlet UIButton *btnDownloadFile; 
  5.   
  6. @end 

NSURLConnectionViewController.m

 
  1. #import "NSURLConnectionViewController.h" 
  2. #import "UIButton+BeautifulButton.h" 
  3.   
  4. @interface NSURLConnectionViewController () 
  5. - (void)layoutUI; 
  6. - (void)saveDataToDisk:(NSData *)data; 
  7. @end 
  8.   
  9. @implementation NSURLConnectionViewController 
  10.   
  11. - (void)viewDidLoad { 
  12.     [super viewDidLoad]; 
  13.       
  14.     [self layoutUI]; 
  15.   
  16. - (void)didReceiveMemoryWarning { 
  17.     [super didReceiveMemoryWarning]; 
  18.     // Dispose of any resources that can be recreated. 
  19.   
  20. - (void)layoutUI { 
  21.     self.navigationItem.title = kTitleOfNSURLConnection; 
  22.     self.view.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1.000]; 
  23.       
  24.     [_btnDownloadFile beautifulButton:nil]; 
  25.   
  26. - (void)saveDataToDisk:(NSData *)data { 
  27.     //数据接收完保存文件;注意苹果官方要求:下载数据只能保存在缓存目录(/Library/Caches) 
  28.     NSString *savePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; 
  29.     savePath = [savePath stringByAppendingPathComponent:_lblFileName.text]; 
  30.     [data writeToFile:savePath atomically:YES]; //writeToFile: 方法:如果 savePath 文件存在,他会执行覆盖 
  31.   
  32. - (IBAction)downloadFile:(id)sender { 
  33.     _lblMessage.text = @"下载中..."
  34.       
  35.     NSString *fileURLStr = kFileURLStr; 
  36.     //编码操作;对应的解码操作是用 stringByRemovingPercentEncoding 方法 
  37.     fileURLStr = [fileURLStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 
  38.     NSURL *fileURL = [NSURL URLWithString:fileURLStr]; 
  39.       
  40.     //创建请求 
  41.     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:fileURL]; 
  42.       
  43.     //创建连接;Apple 提供的处理一般请求的两种方法,他们不需要进行一系列的 NSURLConnectionDataDelegate 委托协议方法操作,简洁直观 
  44.     //方法一:发送一个同步请求;不建议使用,因为当前线程是主线程的话,会造成线程阻塞,一般比较少用 
  45. //    NSURLResponse *response; 
  46. //    NSError *connectionError; 
  47. //    NSData *data = [NSURLConnection sendSynchronousRequest:request 
  48. //                                         returningResponse:&response 
  49. //                                                     error:&connectionError]; 
  50. //    if (!connectionError) { 
  51. //        [self saveDataToDisk:data]; 
  52. //        NSLog(@"保存成功"); 
  53. //         
  54. //        _lblMessage.text = @"下载完成"; 
  55. //    } else { 
  56. //        NSLog(@"下载失败,错误信息:%@", connectionError.localizedDescription); 
  57. //         
  58. //        _lblMessage.text = @"下载失败"; 
  59. //    } 
  60.       
  61.     //方法二:发送一个异步请求 
  62.     [NSURLConnection sendAsynchronousRequest:request 
  63.                                        queue:[NSOperationQueue mainQueue] 
  64.                            completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { 
  65.                                if (!connectionError) { 
  66.                                    [self saveDataToDisk:data]; 
  67.                                    NSLog(@"保存成功"); 
  68.                                      
  69.                                    _lblMessage.text = @"下载完成"
  70.                                      
  71.                                } else { 
  72.                                    NSLog(@"下载失败,错误信息:%@", connectionError.localizedDescription); 
  73.                                      
  74.                                    _lblMessage.text = @"下载失败"
  75.                                } 
  76.                            }]; 
  77.   
  78. @end 

#p#

NSURLConnectionViewController.xib

 
  1. [?xml version="1.0" encoding="UTF-8" standalone="no"?] 
  2. [document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="6211" systemVersion="14A298i" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES"
  3.     [dependencies] 
  4.         [plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="6204"/] 
  5.     [/dependencies] 
  6.     [objects] 
  7.         [placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner" customClass="NSURLConnectionViewController"
  8.             [connections] 
  9.                 [outlet property="btnDownloadFile" destination="mwt-p9-tRE" id="ZVc-6S-ES3"/] 
  10.                 [outlet property="lblFileName" destination="dlB-Qn-eOO" id="NdS-9n-7KX"/] 
  11.                 [outlet property="lblMessage" destination="qlQ-nM-BXU" id="tRe-SR-AQE"/] 
  12.                 [outlet property="view" destination="i5M-Pr-FkT" id="sfx-zR-JGt"/] 
  13.             [/connections] 
  14.         [/placeholder] 
  15.         [placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/] 
  16.         [view clearsContextBeforeDrawing="NO" contentMode="scaleToFill" id="i5M-Pr-FkT"
  17.             [rect key="frame" x="0.0" y="0.0" width="600" height="600"/] 
  18.             [autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/] 
  19.             [subviews] 
  20.                 [label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="metro_demo使用Highcharts实现图表展示.zip" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="dlB-Qn-eOO"
  21.                     [rect key="frame" x="145" y="104" width="309.5" height="18"/] 
  22.                     [fontDescription key="fontDescription" type="boldSystem" pointSize="15"/] 
  23.                     [color key="textColor" cocoaTouchSystemColor="darkTextColor"/] 
  24.                     [nil key="highlightedColor"/] 
  25.                 [/label] 
  26.                 [button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="mwt-p9-tRE"
  27.                     [rect key="frame" x="250" y="520" width="100" height="40"/] 
  28.                     [constraints] 
  29.                         [constraint firstAttribute="width" constant="100" id="I5D-tA-ffH"/] 
  30.                         [constraint firstAttribute="height" constant="40" id="Y8C-D4-IVr"/] 
  31.                     [/constraints] 
  32.                     [state key="normal" title="下载"
  33.                         [color key="titleShadowColor" white="0.5" alpha="1" colorSpace="calibratedWhite"/] 
  34.                     [/state] 
  35.                     [connections] 
  36.                         [action selector="downloadFile:" destination="-1" eventType="touchUpInside" id="MK4-Yk-IOk"/] 
  37.                     [/connections] 
  38.                 [/button] 
  39.                 [label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Label" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="qlQ-nM-BXU"
  40.                     [rect key="frame" x="145" y="140" width="37.5" height="18"/] 
  41.                     [fontDescription key="fontDescription" type="system" pointSize="15"/] 
  42.                     [color key="textColor" red="0.0" green="0.50196081399917603" blue="1" alpha="1" colorSpace="calibratedRGB"/] 
  43.                     [nil key="highlightedColor"/] 
  44.                     [userDefinedRuntimeAttributes] 
  45.                         [userDefinedRuntimeAttribute type="string" keyPath="text" value=""/] 
  46.                     [/userDefinedRuntimeAttributes] 
  47.                 [/label] 
  48.             [/subviews] 
  49.             [color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/] 
  50.             [constraints] 
  51.                 [constraint firstAttribute="centerX" secondItem="dlB-Qn-eOO" secondAttribute="centerX" id="gNK-NO-rth"/] 
  52.                 [constraint firstItem="dlB-Qn-eOO" firstAttribute="top" secondItem="i5M-Pr-FkT" secondAttribute="top" constant="104" id="hwU-O2-Fed"/] 
  53.                 [constraint firstAttribute="centerX" secondItem="mwt-p9-tRE" secondAttribute="centerX" id="teN-3t-8Gc"/] 
  54.                 [constraint firstItem="qlQ-nM-BXU" firstAttribute="top" secondItem="i5M-Pr-FkT" secondAttribute="top" constant="140" id="w3g-ej-P18"/] 
  55.                 [constraint firstItem="dlB-Qn-eOO" firstAttribute="leading" secondItem="qlQ-nM-BXU" secondAttribute="leading" constant="0.5" id="wMU-pU-z9f"/] 
  56.                 [constraint firstAttribute="bottom" secondItem="mwt-p9-tRE" secondAttribute="bottom" constant="40" id="yBq-He-Jv8"/] 
  57.             [/constraints] 
  58.         [/view] 
  59.     [/objects] 
  60. [/document] 

NSURLConnectionDelegateViewController.h

 
  1. #import @interface NSURLConnectionDelegateViewController : UIViewController 
  2. @property (strong, nonatomic) NSMutableData *mDataReceive; 
  3. @property (assign, nonatomic) NSUInteger totalDataLength; 
  4.   
  5. @property (strong, nonatomic) IBOutlet UILabel *lblFileName; 
  6. @property (strong, nonatomic) IBOutlet UIProgressView *progVDownloadFile; 
  7. @property (strong, nonatomic) IBOutlet UILabel *lblMessage; 
  8. @property (strong, nonatomic) IBOutlet UIButton *btnDownloadFile; 
  9.   
  10. @end 

NSURLConnectionDelegateViewController.m

 
  1. #import "NSURLConnectionDelegateViewController.h" 
  2. #import "UIButton+BeautifulButton.h" 
  3.   
  4. @interface NSURLConnectionDelegateViewController () 
  5. - (void)layoutUI; 
  6. - (BOOL)isExistCacheInMemory:(NSURLRequest *)request; 
  7. - (void)updateProgress; 
  8. @end 
  9.   
  10. @implementation NSURLConnectionDelegateViewController 
  11.   
  12. - (void)viewDidLoad { 
  13.     [super viewDidLoad]; 
  14.       
  15.     [self layoutUI]; 
  16.   
  17. - (void)didReceiveMemoryWarning { 
  18.     [super didReceiveMemoryWarning]; 
  19.     // Dispose of any resources that can be recreated. 
  20.   
  21. - (void)layoutUI { 
  22.     self.navigationItem.title = kTitleOfNSURLConnectionDelegate; 
  23.     self.view.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1.000]; 
  24.       
  25.     [_btnDownloadFile beautifulButton:nil]; 
  26.   
  27. - (BOOL)isExistCacheInMemory:(NSURLRequest *)request { 
  28.     BOOL isExistCache = NO; 
  29.     NSURLCache *cache = [NSURLCache sharedURLCache]; 
  30.     [cache setMemoryCapacity:1024 * 1024]; //1M 
  31.       
  32.     NSCachedURLResponse *response = [cache cachedResponseForRequest:request]; 
  33.     if (response != nil) { 
  34.         NSLog(@"内存中存在对应请求的响应缓存"); 
  35.         isExistCache = YES; 
  36.     } 
  37.     return isExistCache; 
  38.   
  39. - (void)updateProgress { 
  40.     NSUInteger receiveDataLength = _mDataReceive.length; 
  41.     if (receiveDataLength == _totalDataLength) { 
  42.         _lblMessage.text = @"下载完成"
  43.         kApplication.networkActivityIndicatorVisible = NO; 
  44.     } else { 
  45.         _lblMessage.text = @"下载中..."
  46.         kApplication.networkActivityIndicatorVisible = YES; 
  47.         _progVDownloadFile.progress = (float)receiveDataLength / _totalDataLength; 
  48.     } 
  49.   
  50. - (IBAction)downloadFile:(id)sender { 
  51.     /* 
  52.      此例子更多的是希望大家了解代理方法接收响应数据的过程,实际开发中也不可能使用这种方法进行文件下载。这种下载有个致命的问题:无法进行大文件下载。因为代理方法在接收数据时虽然表面看起来是每次读取一部分响应数据,事实上它只有一次请求并且也只接收了一次服务器响应,只是当响应数据较大时系统会重复调用数据接收方法,每次将已读取的数据拿出一部分交给数据接收方法而已。在这个过程中其实早已经将响应数据全部拿到,只是分批交给开发者而已。这样一来对于几个G的文件如果进行下载,那么不用说是真机下载了,就算是模拟器恐怕也是不现实的。 
  53.      实际开发文件下载的时候不管是通过代理方法还是静态方法执行请求和响应,我们都会分批请求数据,而不是一次性请求数据。假设一个文件有1G,那么只要每次请求1M的数据,请求1024次也就下载完了。那么如何让服务器每次只返回1M的数据呢? 
  54.      在网络开发中可以在请求的头文件中设置一个Range信息,它代表请求数据的大小。通过这个字段配合服务器端可以精确的控制每次服务器响应的数据范围。例如指定bytes=0-1023,然后在服务器端解析Range信息,返回该文件的0到1023之间的数据的数据即可(共1024Byte)。这样,只要在每次发送请求控制这个头文件信息就可以做到分批请求。 
  55.      当然,为了让整个数据保持完整,每次请求的数据都需要逐步追加直到整个文件请求完成。但是如何知道整个文件的大小?其实在此例子通过头文件信息获取整个文件大小,他请求整个数据,这样做对分段下载就没有任何意义了。所幸在WEB开发中我们还有另一种请求方法“HEAD”,通过这种请求服务器只会响应头信息,其他数据不会返回给客户端,这样一来整个数据的大小也就可以得到了。 
  56.      */ 
  57.       
  58.       
  59.     NSString *fileURLStr = kFileURLStr; 
  60.     //编码操作;对应的解码操作是用 stringByRemovingPercentEncoding 方法 
  61.     fileURLStr = [fileURLStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 
  62.     NSURL *fileURL = [NSURL URLWithString:fileURLStr]; 
  63.       
  64.     /*创建请求 
  65.      cachePolicy:缓存策略 
  66.      1、NSURLRequestUseProtocolCachePolicy 协议缓存,根据 response 中的 Cache-Control 字段判断缓存是否有效,如果缓存有效则使用缓存数据否则重新从服务器请求 
  67.      2、NSURLRequestReloadIgnoringLocalCacheData 不使用缓存,直接请求新数据 
  68.      3、NSURLRequestReloadIgnoringCacheData 等同于 NSURLRequestReloadIgnoringLocalCacheData 
  69.      4、NSURLRequestReturnCacheDataElseLoad 直接使用缓存数据不管是否有效,没有缓存则重新请求 
  70.      5、NSURLRequestReturnCacheDataDontLoad 直接使用缓存数据不管是否有效,没有缓存数据则失败 
  71.        
  72.      timeoutInterval:超时时间设置(默认60s) 
  73.      */ 
  74.     NSURLRequest *request = [[NSURLRequest alloc] initWithURL:fileURL 
  75.                                                   cachePolicy:NSURLRequestUseProtocolCachePolicy 
  76.                                               timeoutInterval:60.0]; 
  77.     if ([self isExistCacheInMemory:request]) { 
  78.         request = [[NSURLRequest alloc] initWithURL:fileURL 
  79.                                         cachePolicy:NSURLRequestReturnCacheDataDontLoad 
  80.                                     timeoutInterval:60.0]; 
  81.     } 
  82.       
  83.     //创建连接,异步操作 
  84.     NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request 
  85.                                                                   delegate:self]; 
  86.     [connection start]; //启动连接 
  87.   
  88. #pragma mark - NSURLConnectionDataDelegate 
  89. - (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response { 
  90.     NSLog(@"即将发送请求"); 
  91.       
  92.     return request; 
  93.   
  94. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 
  95.     NSLog(@"已经接收到响应"); 
  96.       
  97.     _mDataReceive = [NSMutableData new]; 
  98.     _progVDownloadFile.progress = 0.0
  99.       
  100.     //通过响应头中的 Content-Length 获取到整个响应的总长度 
  101.     /* 
  102.      { 
  103.      "Accept-Ranges" = bytes; 
  104.      "Cache-Control" = "max-age=7776000"; 
  105.      "Content-Length" = 592441; 
  106.      "Content-Type" = "application/x-zip-compressed"; 
  107.      Date = "Wed, 02 Sep 2015 13:17:01 GMT"; 
  108.      Etag = "\"d8f617371f9cd01:0\""; 
  109.      "Last-Modified" = "Mon, 01 Jun 2015 03:58:27 GMT"; 
  110.      Server = "Microsoft-IIS/7.5"; 
  111.      "X-Powered-By" = "ASP.NET"; 
  112.      } 
  113.      */ 
  114.     NSDictionary *dicHeaderField = [(NSHTTPURLResponse *)response allHeaderFields]; 
  115.     _totalDataLength = [[dicHeaderField objectForKey:@"Content-Length"] integerValue]; 
  116.   
  117. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 
  118.     NSLog(@"已经接收到响应数据,数据长度为%lu字节...", (unsigned long)[data length]); 
  119.       
  120.     [_mDataReceive appendData:data]; //连续接收数据 
  121.     [self updateProgress]; //连续更新进度条 
  122.   
  123. - (void)connectionDidFinishLoading:(NSURLConnection *)connection { 
  124.     NSLog(@"已经接收完所有响应数据"); 
  125.       
  126.     NSString *savePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; 
  127.     savePath = [savePath stringByAppendingPathComponent:_lblFileName.text]; 
  128.     [_mDataReceive writeToFile:savePath atomically:YES]; 
  129.   
  130. - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { 
  131.     //如果连接超时或者连接地址错误可能就会报错 
  132.     NSLog(@"连接错误,错误信息:%@", error.localizedDescription); 
  133.       
  134.     _lblMessage.text = @"连接错误"
  135.   
  136. @end 

NSURLConnectionDelegateViewController.xib

 
  1. [?xml version="1.0" encoding="UTF-8" standalone="no"?] 
  2. [document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="7706" systemVersion="14E46" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES"
  3.     [dependencies] 
  4.         [deployment identifier="iOS"/] 
  5.         [plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="7703"/] 
  6.     [/dependencies] 
  7.     [objects] 
  8.         [placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner" customClass="NSURLConnectionDelegateViewController"
  9.             [connections] 
  10.                 [outlet property="btnDownloadFile" destination="mwt-p9-tRE" id="ZVc-6S-ES3"/] 
  11.                 [outlet property="lblFileName" destination="dlB-Qn-eOO" id="vJk-jh-Y2c"/] 
  12.                 [outlet property="lblMessage" destination="qlQ-nM-BXU" id="tRe-SR-AQE"/] 
  13.                 [outlet property="progVDownloadFile" destination="Me3-m2-iC4" id="PtK-m7-j5N"/] 
  14.                 [outlet property="view" destination="i5M-Pr-FkT" id="sfx-zR-JGt"/] 
  15.             [/connections] 
  16.         [/placeholder] 
  17.         [placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/] 
  18.         [view clearsContextBeforeDrawing="NO" contentMode="scaleToFill" id="i5M-Pr-FkT"
  19.             [rect key="frame" x="0.0" y="0.0" width="600" height="600"/] 
  20.             [autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/] 
  21.             [subviews] 
  22.                 [label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="metro_demo使用Highcharts实现图表展示.zip" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="dlB-Qn-eOO"
  23.                     [rect key="frame" x="145" y="104" width="309.5" height="18"/] 
  24.                     [fontDescription key="fontDescription" type="boldSystem" pointSize="15"/] 
  25.                     [color key="textColor" cocoaTouchSystemColor="darkTextColor"/] 
  26.                     [nil key="highlightedColor"/] 
  27.                 [/label] 
  28.                 [button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="mwt-p9-tRE"
  29.                     [rect key="frame" x="250" y="520" width="100" height="40"/] 
  30.                     [constraints] 
  31.                         [constraint firstAttribute="width" constant="100" id="I5D-tA-ffH"/] 
  32.                         [constraint firstAttribute="height" constant="40" id="Y8C-D4-IVr"/] 
  33.                     [/constraints] 
  34.                     [state key="normal" title="下载"
  35.                         [color key="titleShadowColor" white="0.5" alpha="1" colorSpace="calibratedWhite"/] 
  36.                     [/state] 
  37.                     [connections] 
  38.                         [action selector="downloadFile:" destination="-1" eventType="touchUpInside" id="iGc-6N-bsZ"/] 
  39.                     [/connections] 
  40.                 [/button] 
  41.                 [progressView opaque="NO" contentMode="scaleToFill" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="Me3-m2-iC4"
  42.                     [rect key="frame" x="145" y="160" width="310" height="2"/] 
  43.                     [constraints] 
  44.                         [constraint firstAttribute="height" constant="2" id="I50-Zx-DwT"/] 
  45.                         [constraint firstAttribute="width" constant="310" id="wdS-eD-Tkc"/] 
  46.                     [/constraints] 
  47.                 [/progressView] 
  48.                 [label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Label" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="qlQ-nM-BXU"
  49.                     [rect key="frame" x="145" y="180" width="37.5" height="18"/] 
  50.                     [fontDescription key="fontDescription" type="system" pointSize="15"/] 
  51.                     [color key="textColor" red="0.0" green="0.50196081399917603" blue="1" alpha="1" colorSpace="calibratedRGB"/] 
  52.                     [nil key="highlightedColor"/] 
  53.                     [userDefinedRuntimeAttributes] 
  54.                         [userDefinedRuntimeAttribute type="string" keyPath="text" value=""/] 
  55.                     [/userDefinedRuntimeAttributes] 
  56.                 [/label] 
  57.             [/subviews] 
  58.             [color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/] 
  59.             [constraints] 
  60.                 [constraint firstAttribute="centerX" secondItem="Me3-m2-iC4" secondAttribute="centerX" id="Ya8-bM-TaA"/] 
  61.                 [constraint firstItem="Me3-m2-iC4" firstAttribute="top" secondItem="i5M-Pr-FkT" secondAttribute="top" constant="160" id="bOY-B5-is2"/] 
  62.                 [constraint firstAttribute="centerX" secondItem="dlB-Qn-eOO" secondAttribute="centerX" id="gNK-NO-rth"/] 
  63.                 [constraint firstItem="dlB-Qn-eOO" firstAttribute="top" secondItem="i5M-Pr-FkT" secondAttribute="top" constant="104" id="hwU-O2-Fed"/] 
  64.                 [constraint firstItem="qlQ-nM-BXU" firstAttribute="leading" secondItem="Me3-m2-iC4" secondAttribute="leading" id="lus-oi-9SA"/] 
  65.                 [constraint firstAttribute="centerX" secondItem="mwt-p9-tRE" secondAttribute="centerX" id="teN-3t-8Gc"/] 
  66.                 [constraint firstItem="qlQ-nM-BXU" firstAttribute="top" secondItem="i5M-Pr-FkT" secondAttribute="top" constant="180" id="w3g-ej-P18"/] 
  67.                 [constraint firstAttribute="bottom" secondItem="mwt-p9-tRE" secondAttribute="bottom" constant="40" id="yBq-He-Jv8"/] 
  68.             [/constraints] 
  69.         [/view] 
  70.     [/objects] 
  71. [/document] 

NSURLSessionViewController.h

 
  1. #import @interface NSURLSessionViewController : UIViewController 
  2. @property (strong, nonatomic) IBOutlet UILabel *lblFileName; 
  3. @property (strong, nonatomic) IBOutlet UILabel *lblMessage; 
  4. @property (strong, nonatomic) IBOutlet UIButton *btnDownloadFile; 
  5.   
  6. @end 

NSURLSessionViewController.m

 
  1. #import "NSURLSessionViewController.h" 
  2. #import "UIButton+BeautifulButton.h" 
  3.   
  4. @interface NSURLSessionViewController () 
  5. - (void)layoutUI; 
  6. @end 
  7.   
  8. @implementation NSURLSessionViewController 
  9.   
  10. - (void)viewDidLoad { 
  11.     [super viewDidLoad]; 
  12.       
  13.     [self layoutUI]; 
  14.   
  15. - (void)didReceiveMemoryWarning { 
  16.     [super didReceiveMemoryWarning]; 
  17.     // Dispose of any resources that can be recreated. 
  18.   
  19. - (void)layoutUI { 
  20.     self.navigationItem.title = kTitleOfNSURLSession; 
  21.     self.view.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1.000]; 
  22.       
  23.     [_btnDownloadFile beautifulButton:nil]; 
  24.   
  25. - (IBAction)downloadFile:(id)sender { 
  26.     _lblMessage.text = @"下载中..."
  27.       
  28.     NSString *fileURLStr = kFileURLStr; 
  29.     //编码操作;对应的解码操作是用 stringByRemovingPercentEncoding 方法 
  30.     fileURLStr = [fileURLStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 
  31.     NSURL *fileURL = [NSURL URLWithString:fileURLStr]; 
  32.       
  33.     //创建请求 
  34.     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:fileURL]; 
  35.       
  36.     //创建会话(这里使用了一个全局会话) 
  37.     NSURLSession *session = [NSURLSession sharedSession]; 
  38.       
  39.     //创建下载任务,并且启动他;在非主线程中执行 
  40.     NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) { 
  41.         __block void (^updateUI)(); //声明用于主线程更新 UI 的代码块 
  42.           
  43.         if (!error) { 
  44.             NSLog(@"下载后的临时保存路径:%@", location); 
  45.               
  46.             NSString *savePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; 
  47.             savePath = [savePath stringByAppendingPathComponent:_lblFileName.text]; 
  48.             NSURL *saveURL = [NSURL fileURLWithPath:savePath]; 
  49.             NSError *saveError; 
  50.             NSFileManager *fileManager = [NSFileManager defaultManager]; 
  51.             //判断是否存在旧的目标文件,如果存在就先移除;避免无法复制问题 
  52.             if ([fileManager fileExistsAtPath:savePath]) { 
  53.                 [fileManager removeItemAtPath:savePath error:&saveError]; 
  54.                 if (saveError) { 
  55.                     NSLog(@"移除旧的目标文件失败,错误信息:%@", saveError.localizedDescription); 
  56.                       
  57.                     updateUI = ^ { 
  58.                         _lblMessage.text = @"下载失败"
  59.                     }; 
  60.                 } 
  61.             } 
  62.             if (!saveError) { 
  63.                 //把源文件复制到目标文件,当目标文件存在时,会抛出一个错误到 error 参数指向的对象实例 
  64.                 //方法一(path 不能有 file:// 前缀) 
  65.                 //                [fileManager copyItemAtPath:[location path] 
  66.                 //                                     toPath:savePath 
  67.                 //                                      error:&saveError]; 
  68.                   
  69.                 //方法二 
  70.                 [fileManager copyItemAtURL:location 
  71.                                      toURL:saveURL 
  72.                                      error:&saveError]; 
  73.                   
  74.                 if (!saveError) { 
  75.                     NSLog(@"保存成功"); 
  76.                       
  77.                     updateUI = ^ { 
  78.                         _lblMessage.text = @"下载完成"
  79.                     }; 
  80.                 } else { 
  81.                     NSLog(@"保存失败,错误信息:%@", saveError.localizedDescription); 
  82.                       
  83.                     updateUI = ^ { 
  84.                         _lblMessage.text = @"下载失败"
  85.                     }; 
  86.                 } 
  87.             } 
  88.               
  89.         } else { 
  90.             NSLog(@"下载失败,错误信息:%@", error.localizedDescription); 
  91.               
  92.             updateUI = ^ { 
  93.                 _lblMessage.text = @"下载失败"
  94.             }; 
  95.         } 
  96.           
  97.         dispatch_async(dispatch_get_main_queue(), updateUI); //使用主队列异步方式(主线程)执行更新 UI 的代码块 
  98.     }]; 
  99.     [downloadTask resume]; //恢复线程,启动任务 
  100.   
  101. @end 

#p#

NSURLSessionViewController.xib

 
  1. [?xml version="1.0" encoding="UTF-8" standalone="no"?] 
  2. [document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="7706" systemVersion="14E46" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES"
  3.     [dependencies] 
  4.         [deployment identifier="iOS"/] 
  5.         [plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="7703"/] 
  6.     [/dependencies] 
  7.     [objects] 
  8.         [placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner" customClass="NSURLSessionViewController"
  9.             [connections] 
  10.                 [outlet property="btnDownloadFile" destination="mwt-p9-tRE" id="ZVc-6S-ES3"/] 
  11.                 [outlet property="lblFileName" destination="dlB-Qn-eOO" id="NdS-9n-7KX"/] 
  12.                 [outlet property="lblMessage" destination="qlQ-nM-BXU" id="tRe-SR-AQE"/] 
  13.                 [outlet property="view" destination="i5M-Pr-FkT" id="sfx-zR-JGt"/] 
  14.             [/connections] 
  15.         [/placeholder] 
  16.         [placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/] 
  17.         [view clearsContextBeforeDrawing="NO" contentMode="scaleToFill" id="i5M-Pr-FkT"
  18.             [rect key="frame" x="0.0" y="0.0" width="600" height="600"/] 
  19.             [autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/] 
  20.             [subviews] 
  21.                 [label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="metro_demo使用Highcharts实现图表展示.zip" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="dlB-Qn-eOO"
  22.                     [rect key="frame" x="145" y="104" width="309.5" height="18"/] 
  23.                     [fontDescription key="fontDescription" type="boldSystem" pointSize="15"/] 
  24.                     [color key="textColor" cocoaTouchSystemColor="darkTextColor"/] 
  25.                     [nil key="highlightedColor"/] 
  26.                 [/label] 
  27.                 [button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="mwt-p9-tRE"
  28.                     [rect key="frame" x="250" y="520" width="100" height="40"/] 
  29.                     [constraints] 
  30.                         [constraint firstAttribute="width" constant="100" id="I5D-tA-ffH"/] 
  31.                         [constraint firstAttribute="height" constant="40" id="Y8C-D4-IVr"/] 
  32.                     [/constraints] 
  33.                     [state key="normal" title="下载"
  34.                         [color key="titleShadowColor" white="0.5" alpha="1" colorSpace="calibratedWhite"/] 
  35.                     [/state] 
  36.                     [connections] 
  37.                         [action selector="downloadFile:" destination="-1" eventType="touchUpInside" id="MK4-Yk-IOk"/] 
  38.                     [/connections] 
  39.                 [/button] 
  40.                 [label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Label" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="qlQ-nM-BXU"
  41.                     [rect key="frame" x="145" y="140" width="37.5" height="18"/] 
  42.                     [fontDescription key="fontDescription" type="system" pointSize="15"/] 
  43.                     [color key="textColor" red="0.0" green="0.50196081399917603" blue="1" alpha="1" colorSpace="calibratedRGB"/] 
  44.                     [nil key="highlightedColor"/] 
  45.                     [userDefinedRuntimeAttributes] 
  46.                         [userDefinedRuntimeAttribute type="string" keyPath="text" value=""/] 
  47.                     [/userDefinedRuntimeAttributes] 
  48.                 [/label] 
  49.             [/subviews] 
  50.             [color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/] 
  51.             [constraints] 
  52.                 [constraint firstAttribute="centerX" secondItem="dlB-Qn-eOO" secondAttribute="centerX" id="gNK-NO-rth"/] 
  53.                 [constraint firstItem="dlB-Qn-eOO" firstAttribute="top" secondItem="i5M-Pr-FkT" secondAttribute="top" constant="104" id="hwU-O2-Fed"/] 
  54.                 [constraint firstAttribute="centerX" secondItem="mwt-p9-tRE" secondAttribute="centerX" id="teN-3t-8Gc"/] 
  55.                 [constraint firstItem="qlQ-nM-BXU" firstAttribute="top" secondItem="i5M-Pr-FkT" secondAttribute="top" constant="140" id="w3g-ej-P18"/] 
  56.                 [constraint firstItem="dlB-Qn-eOO" firstAttribute="leading" secondItem="qlQ-nM-BXU" secondAttribute="leading" constant="0.5" id="wMU-pU-z9f"/] 
  57.                 [constraint firstAttribute="bottom" secondItem="mwt-p9-tRE" secondAttribute="bottom" constant="40" id="yBq-He-Jv8"/] 
  58.             [/constraints] 
  59.         [/view] 
  60.     [/objects] 
  61. [/document] 

NSURLSessionDelegateViewController.h

 
  1. #import @interface NSURLSessionDelegateViewController : UIViewController @property (strong, nonatomic) NSURLSessionDownloadTask *downloadTask; 
  2.   
  3. @property (strong, nonatomic) IBOutlet UILabel *lblFileName; 
  4. @property (strong, nonatomic) IBOutlet UIProgressView *progVDownloadFile; 
  5. @property (strong, nonatomic) IBOutlet UILabel *lblMessage; 
  6. @property (strong, nonatomic) IBOutlet UIButton *btnDownloadFile; 
  7. @property (strong, nonatomic) IBOutlet UIButton *btnCancel; 
  8. @property (strong, nonatomic) IBOutlet UIButton *btnSuspend; 
  9. @property (strong, nonatomic) IBOutlet UIButton *btnResume; 
  10.   
  11. @end 

NSURLSessionDelegateViewController.m

 
  1. #import "NSURLSessionDelegateViewController.h" 
  2. #import "UIButton+BeautifulButton.h" 
  3.   
  4. @interface NSURLSessionDelegateViewController () 
  5. - (void)layoutUI; 
  6. - (NSURLSession *)defaultSession; 
  7. - (NSURLSession *)backgroundSession; 
  8. - (void)updateProgress:(int64_t)receiveDataLength totalDataLength:(int64_t)totalDataLength; 
  9. @end 
  10.   
  11. @implementation NSURLSessionDelegateViewController 
  12.   
  13. - (void)viewDidLoad { 
  14.     [super viewDidLoad]; 
  15.       
  16.     [self layoutUI]; 
  17.   
  18. - (void)didReceiveMemoryWarning { 
  19.     [super didReceiveMemoryWarning]; 
  20.     // Dispose of any resources that can be recreated. 
  21.   
  22. - (void)layoutUI { 
  23.     self.navigationItem.title = kTitleOfNSURLSessionDelegate; 
  24.     self.view.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1.000]; 
  25.       
  26.     [_btnDownloadFile beautifulButton:nil]; 
  27.     [_btnCancel beautifulButton:[UIColor redColor]]; 
  28.     [_btnSuspend beautifulButton:[UIColor purpleColor]]; 
  29.     [_btnResume beautifulButton:[UIColor orangeColor]]; 
  30.   
  31. - (NSURLSession *)defaultSession { 
  32.     /* 
  33.      NSURLSession 支持进程三种会话: 
  34.      1、defaultSessionConfiguration:进程内会话(默认会话),用硬盘来缓存数据。 
  35.      2、ephemeralSessionConfiguration:临时的进程内会话(内存),不会将 cookie、缓存储存到本地,只会放到内存中,当应用程序退出后数据也会消失。 
  36.      3、backgroundSessionConfiguration:后台会话,相比默认会话,该会话会在后台开启一个线程进行网络数据处理。 
  37.      */ 
  38.   
  39.     //创建会话配置「进程内会话」 
  40.     NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration]; 
  41.     sessionConfiguration.timeoutIntervalForRequest = 60.0//请求超时时间;默认为60秒 
  42.     sessionConfiguration.allowsCellularAccess = YES; //是否允许蜂窝网络访问(2G/3G/4G) 
  43.     sessionConfiguration.HTTPMaximumConnectionsPerHost = 4//限制每次最多连接数;在 iOS 中默认值为4 
  44.       
  45.     //创建会话 
  46.     NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration 
  47.                                                           delegate:self 
  48.                                                      delegateQueue:nil]; 
  49.     return session; 
  50.   
  51. - (NSURLSession *)backgroundSession { 
  52.     static NSURLSession *session; 
  53.     static dispatch_once_t onceToken; 
  54.     dispatch_once(&onceToken, ^{ //应用程序生命周期内,只执行一次;保证只有一个「后台会话」 
  55.         //创建会话配置「后台会话」 
  56.         NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"KMDownloadFile.NSURLSessionDelegateViewController"]; 
  57.         sessionConfiguration.timeoutIntervalForRequest = 60.0//请求超时时间;默认为60秒 
  58.         sessionConfiguration.allowsCellularAccess = YES; //是否允许蜂窝网络访问(2G/3G/4G) 
  59.         sessionConfiguration.HTTPMaximumConnectionsPerHost = 4//限制每次最多连接数;在 iOS 中默认值为4 
  60.         sessionConfiguration.discretionary = YES; //是否自动选择最佳网络访问,仅对「后台会话」有效 
  61.           
  62.         //创建会话 
  63.         session = [NSURLSession sessionWithConfiguration:sessionConfiguration 
  64.                                                 delegate:self 
  65.                                            delegateQueue:nil]; 
  66.     }); 
  67.     return session; 
  68.   
  69. - (void)updateProgress:(int64_t)receiveDataLength totalDataLength:(int64_t)totalDataLength; { 
  70.     dispatch_async(dispatch_get_main_queue(), ^{ //使用主队列异步方式(主线程)执行更新 UI 操作 
  71.         if (receiveDataLength == totalDataLength) { 
  72.             _lblMessage.text = @"下载完成"
  73.             kApplication.networkActivityIndicatorVisible = NO; 
  74.         } else { 
  75.             _lblMessage.text = @"下载中..."
  76.             kApplication.networkActivityIndicatorVisible = YES; 
  77.             _progVDownloadFile.progress = (float)receiveDataLength / totalDataLength; 
  78.         } 
  79.     }); 
  80.   
  81. - (IBAction)downloadFile:(id)sender { 
  82.     NSString *fileURLStr = kFileURLStr; 
  83.     //编码操作;对应的解码操作是用 stringByRemovingPercentEncoding 方法 
  84.     fileURLStr = [fileURLStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 
  85.     NSURL *fileURL = [NSURL URLWithString:fileURLStr]; 
  86.       
  87.     //创建请求 
  88.     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:fileURL]; 
  89.       
  90.     //创建会话「进程内会话」;如要用「后台会话」就使用自定义的[self backgroundSession] 方法 
  91.     NSURLSession *session = [self defaultSession]; 
  92.       
  93.     //创建下载任务,并且启动他;在非主线程中执行 
  94.     _downloadTask = [session downloadTaskWithRequest:request]; 
  95.     [_downloadTask resume]; 
  96.       
  97.     /* 
  98.      会话任务状态 
  99.      typedef NS_ENUM(NSInteger, NSURLSessionTaskState) { 
  100.      NSURLSessionTaskStateRunning = 0, //正在执行 
  101.      NSURLSessionTaskStateSuspended = 1, //已挂起 
  102.      NSURLSessionTaskStateCanceling = 2, //正在取消 
  103.      NSURLSessionTaskStateCompleted = 3, //已完成 
  104.      } NS_ENUM_AVAILABLE(NSURLSESSION_AVAILABLE, 7_0); 
  105.      */ 
  106.   
  107. - (IBAction)cancel:(id)sender { 
  108.     [_downloadTask cancel]; 
  109.   
  110. - (IBAction)suspend:(id)sender { 
  111.     [_downloadTask suspend]; 
  112.     kApplication.networkActivityIndicatorVisible = NO; 
  113.   
  114. - (IBAction)resume:(id)sender { 
  115.     [_downloadTask resume]; 
  116.   
  117. #pragma mark - NSURLSessionDownloadDelegate 
  118. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite { 
  119.     NSLog(@"已经接收到响应数据,数据长度为%lld字节...", totalBytesWritten); 
  120.       
  121.     [self updateProgress:totalBytesWritten totalDataLength:totalBytesExpectedToWrite]; 
  122.   
  123. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location { 
  124.     //下载文件会临时保存,正常流程下系统最终会自动清除此临时文件;保存路径目录根据会话类型而有所不同: 
  125.     //「进程内会话(默认会话)」和「临时的进程内会话(内存)」,路径目录为:/tmp,可以通过 NSTemporaryDirectory() 方法获取 
  126.     //「后台会话」,路径目录为:/Library/Caches/com.apple.nsurlsessiond/Downloads/com.kenmu.KMDownloadFile 
  127.     NSLog(@"已经接收完所有响应数据,下载后的临时保存路径:%@", location); 
  128.       
  129.     __block void (^updateUI)(); //声明用于主线程更新 UI 的代码块 
  130.       
  131.     NSString *savePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; 
  132.     savePath = [savePath stringByAppendingPathComponent:_lblFileName.text]; 
  133.     NSURL *saveURL = [NSURL fileURLWithPath:savePath]; 
  134.     NSError *saveError; 
  135.     NSFileManager *fileManager = [NSFileManager defaultManager]; 
  136.     //判断是否存在旧的目标文件,如果存在就先移除;避免无法复制问题 
  137.     if ([fileManager fileExistsAtPath:savePath]) { 
  138.         [fileManager removeItemAtPath:savePath error:&saveError]; 
  139.         if (saveError) { 
  140.             NSLog(@"移除旧的目标文件失败,错误信息:%@", saveError.localizedDescription); 
  141.               
  142.             updateUI = ^ { 
  143.                 _lblMessage.text = @"下载失败"
  144.             }; 
  145.         } 
  146.     } 
  147.     if (!saveError) { 
  148.         //把源文件复制到目标文件,当目标文件存在时,会抛出一个错误到 error 参数指向的对象实例 
  149.         //方法一(path 不能有 file:// 前缀) 
  150.         //                [fileManager copyItemAtPath:[location path] 
  151.         //                                     toPath:savePath 
  152.         //                                      error:&saveError]; 
  153.           
  154.         //方法二 
  155.         [fileManager copyItemAtURL:location 
  156.                              toURL:saveURL 
  157.                              error:&saveError]; 
  158.           
  159.         if (!saveError) { 
  160.             NSLog(@"保存成功"); 
  161.               
  162.             updateUI = ^ { 
  163.                 _lblMessage.text = @"下载完成"
  164.             }; 
  165.         } else { 
  166.             NSLog(@"保存失败,错误信息:%@", saveError.localizedDescription); 
  167.               
  168.             updateUI = ^ { 
  169.                 _lblMessage.text = @"下载失败"
  170.             }; 
  171.         } 
  172.     } 
  173.       
  174.     dispatch_async(dispatch_get_main_queue(), updateUI); //使用主队列异步方式(主线程)执行更新 UI 的代码块 
  175.   
  176. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { 
  177.     NSLog(@"无论下载成功还是失败,最终都会执行一次"); 
  178.       
  179.     if (error) { 
  180.         NSString *desc = error.localizedDescription; 
  181.         NSLog(@"下载失败,错误信息:%@", desc); 
  182.           
  183.         dispatch_async(dispatch_get_main_queue(), ^{ //使用主队列异步方式(主线程)执行更新 UI 操作 
  184.             _lblMessage.text = [desc isEqualToString:@"cancelled"] ? @"下载已取消" : @"下载失败"
  185.             kApplication.networkActivityIndicatorVisible = NO; 
  186.             _progVDownloadFile.progress = 0.0
  187.         }); 
  188.     } 
  189.   
  190. @end 

NSURLSessionDelegateViewController.xib

 
  1. [?xml version="1.0" encoding="UTF-8" standalone="no"?] 
  2. [document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="7706" systemVersion="14E46" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES"
  3.     [dependencies] 
  4.         [deployment identifier="iOS"/] 
  5.         [plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="7703"/] 
  6.     [/dependencies] 
  7.     [objects] 
  8.         [placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner" customClass="NSURLSessionDelegateViewController"
  9.             [connections] 
  10.                 [outlet property="btnCancel" destination="yMY-kU-iKL" id="QHP-ls-q8P"/] 
  11.                 [outlet property="btnDownloadFile" destination="mwt-p9-tRE" id="ZVc-6S-ES3"/] 
  12.                 [outlet property="btnResume" destination="YSM-n6-UM4" id="RyL-54-rFB"/] 
  13.                 [outlet property="btnSuspend" destination="5kz-pB-9nK" id="1Jj-zV-DXM"/] 
  14.                 [outlet property="lblFileName" destination="dlB-Qn-eOO" id="vJk-jh-Y2c"/] 
  15.                 [outlet property="lblMessage" destination="qlQ-nM-BXU" id="tRe-SR-AQE"/] 
  16.                 [outlet property="progVDownloadFile" destination="Me3-m2-iC4" id="PtK-m7-j5N"/] 
  17.                 [outlet property="view" destination="i5M-Pr-FkT" id="sfx-zR-JGt"/] 
  18.             [/connections] 
  19.         [/placeholder] 
  20.         [placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/] 
  21.         [view clearsContextBeforeDrawing="NO" contentMode="scaleToFill" id="i5M-Pr-FkT"
  22.             [rect key="frame" x="0.0" y="0.0" width="600" height="600"/] 
  23.             [autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/] 
  24.             [subviews] 
  25.                 [label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="metro_demo使用Highcharts实现图表展示.zip" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="dlB-Qn-eOO"
  26.                     [rect key="frame" x="145" y="104" width="309.5" height="18"/] 
  27.                     [fontDescription key="fontDescription" type="boldSystem" pointSize="15"/] 
  28.                     [color key="textColor" cocoaTouchSystemColor="darkTextColor"/] 
  29.                     [nil key="highlightedColor"/] 
  30.                 [/label] 
  31.                 [button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="mwt-p9-tRE"
  32.                     [rect key="frame" x="145" y="520" width="70" height="40"/] 
  33.                     [constraints] 
  34.                         [constraint firstAttribute="width" constant="70" id="I5D-tA-ffH"/] 
  35.                         [constraint firstAttribute="height" constant="40" id="Y8C-D4-IVr"/] 
  36.                     [/constraints] 
  37.                     [state key="normal" title="下载"
  38.                         [color key="titleShadowColor" white="0.5" alpha="1" colorSpace="calibratedWhite"/] 
  39.                     [/state] 
  40.                     [connections] 
  41.                         [action selector="downloadFile:" destination="-1" eventType="touchUpInside" id="iGc-6N-bsZ"/] 
  42.                     [/connections] 
  43.                 [/button] 
  44.                 [progressView opaque="NO" contentMode="scaleToFill" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="Me3-m2-iC4"
  45.                     [rect key="frame" x="145" y="160" width="310" height="2"/] 
  46.                     [constraints] 
  47.                         [constraint firstAttribute="height" constant="2" id="I50-Zx-DwT"/] 
  48.                         [constraint firstAttribute="width" constant="310" id="wdS-eD-Tkc"/] 
  49.                     [/constraints] 
  50.                 [/progressView] 
  51.                 [label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Label" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="qlQ-nM-BXU"
  52.                     [rect key="frame" x="145" y="180" width="37.5" height="18"/] 
  53.                     [fontDescription key="fontDescription" type="system" pointSize="15"/] 
  54.                     [color key="textColor" red="0.0" green="0.50196081399917603" blue="1" alpha="1" colorSpace="calibratedRGB"/] 
  55.                     [nil key="highlightedColor"/] 
  56.                     [userDefinedRuntimeAttributes] 
  57.                         [userDefinedRuntimeAttribute type="string" keyPath="text" value=""/] 
  58.                     [/userDefinedRuntimeAttributes] 
  59.                 [/label] 
  60.                 [button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="5kz-pB-9nK"
  61.                     [rect key="frame" x="305" y="520" width="70" height="40"/] 
  62.                     [constraints] 
  63.                         [constraint firstAttribute="width" constant="70" id="IOm-ve-DPG"/] 
  64.                         [constraint firstAttribute="height" constant="40" id="Kwn-EW-gDl"/] 
  65.                     [/constraints] 
  66.                     [state key="normal" title="挂起"
  67.                         [color key="titleShadowColor" white="0.5" alpha="1" colorSpace="calibratedWhite"/] 
  68.                     [/state] 
  69.                     [connections] 
  70.                         [action selector="suspend:" destination="-1" eventType="touchUpInside" id="O6j-t2-7Lv"/] 
  71.                     [/connections] 
  72.                 [/button] 
  73.                 [button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="YSM-n6-UM4"
  74.                     [rect key="frame" x="385" y="520" width="70" height="40"/] 
  75.                     [constraints] 
  76.                         [constraint firstAttribute="width" constant="70" id="LhS-5f-cG4"/] 
  77.                         [constraint firstAttribute="height" constant="40" id="kzz-1h-4DP"/] 
  78.                     [/constraints] 
  79.                     [state key="normal" title="恢复"
  80.                         [color key="titleShadowColor" white="0.5" alpha="1" colorSpace="calibratedWhite"/] 
  81.                     [/state] 
  82.                     [connections] 
  83.                         [action selector="resume:" destination="-1" eventType="touchUpInside" id="ms9-R9-B9B"/] 
  84.                     [/connections] 
  85.                 [/button] 
  86.                 [button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="yMY-kU-iKL"
  87.                     [rect key="frame" x="225" y="520" width="70" height="40"/] 
  88.                     [constraints] 
  89.                         [constraint firstAttribute="height" constant="40" id="S7b-Pl-qKI"/] 
  90.                         [constraint firstAttribute="width" constant="70" id="gY7-vp-PUz"/] 
  91.                     [/constraints] 
  92.                     [state key="normal" title="取消"
  93.                         [color key="titleShadowColor" white="0.5" alpha="1" colorSpace="calibratedWhite"/] 
  94.                     [/state] 
  95.                     [connections] 
  96.                         [action selector="cancel:" destination="-1" eventType="touchUpInside" id="ITC-zg-bfP"/] 
  97.                     [/connections] 
  98.                 [/button] 
  99.             [/subviews] 
  100.             [color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/] 
  101.             [constraints] 
  102.                 [constraint firstItem="5kz-pB-9nK" firstAttribute="centerY" secondItem="YSM-n6-UM4" secondAttribute="centerY" id="4zt-gy-k65"/] 
  103.                 [constraint firstItem="qlQ-nM-BXU" firstAttribute="leading" secondItem="mwt-p9-tRE" secondAttribute="leading" id="RYu-qM-O8P"/] 
  104.                 [constraint firstAttribute="centerX" secondItem="Me3-m2-iC4" secondAttribute="centerX" id="Ya8-bM-TaA"/] 
  105.                 [constraint firstItem="Me3-m2-iC4" firstAttribute="top" secondItem="i5M-Pr-FkT" secondAttribute="top" constant="160" id="bOY-B5-is2"/] 
  106.                 [constraint firstItem="yMY-kU-iKL" firstAttribute="centerY" secondItem="5kz-pB-9nK" secondAttribute="centerY" id="dBh-1A-sIk"/] 
  107.                 [constraint firstItem="YSM-n6-UM4" firstAttribute="leading" secondItem="5kz-pB-9nK" secondAttribute="trailing" constant="10" id="fYW-Jv-ro2"/] 
  108.                 [constraint firstAttribute="centerX" secondItem="dlB-Qn-eOO" secondAttribute="centerX" id="gNK-NO-rth"/] 
  109.                 [constraint firstItem="dlB-Qn-eOO" firstAttribute="top" secondItem="i5M-Pr-FkT" secondAttribute="top" constant="104" id="hwU-O2-Fed"/] 
  110.                 [constraint firstItem="mwt-p9-tRE" firstAttribute="centerY" secondItem="yMY-kU-iKL" secondAttribute="centerY" id="lGv-fH-Fh7"/] 
  111.                 [constraint firstItem="qlQ-nM-BXU" firstAttribute="leading" secondItem="Me3-m2-iC4" secondAttribute="leading" id="lus-oi-9SA"/] 
  112.                 [constraint firstItem="5kz-pB-9nK" firstAttribute="leading" secondItem="yMY-kU-iKL" secondAttribute="trailing" constant="10" id="oge-T7-1td"/] 
  113.                 [constraint firstItem="qlQ-nM-BXU" firstAttribute="top" secondItem="i5M-Pr-FkT" secondAttribute="top" constant="180" id="w3g-ej-P18"/] 
  114.                 [constraint firstItem="yMY-kU-iKL" firstAttribute="leading" secondItem="mwt-p9-tRE" secondAttribute="trailing" constant="10" id="xCX-1F-xOv"/] 
  115.                 [constraint firstAttribute="bottom" secondItem="mwt-p9-tRE" secondAttribute="bottom" constant="40" id="yBq-He-Jv8"/] 
  116.             [/constraints] 
  117.         [/view] 
  118.     [/objects] 
  119. [/document] 

#p#

AFNetworkingViewController.h

 
  1. #import #import "MBProgressHUD.h" 
  2.   
  3. @interface AFNetworkingViewController : UIViewController 
  4. @property (strong, nonatomic) MBProgressHUD *hud; 
  5.   
  6. @property (strong, nonatomic) IBOutlet UILabel *lblFileName; 
  7. @property (strong, nonatomic) IBOutlet UILabel *lblMessage; 
  8. @property (strong, nonatomic) IBOutlet UIButton *btnDownloadFileByConnection; 
  9. @property (strong, nonatomic) IBOutlet UIButton *btnDownloadFileBySession; 
  10.   
  11. @end 

AFNetworkingViewController.m

 
  1. #import "AFNetworkingViewController.h" 
  2. #import "AFNetworking.h" 
  3. #import "AFNetworkActivityIndicatorManager.h" 
  4. #import "UIButton+BeautifulButton.h" 
  5.   
  6. @interface AFNetworkingViewController () 
  7. - (void)showAlert:(NSString *)msg; 
  8. - (void)checkNetwork; 
  9. - (void)layoutUI; 
  10. - (NSMutableURLRequest *)downloadRequest; 
  11. - (NSURL *)saveURL:(NSURLResponse *)response deleteExistFile:(BOOL)deleteExistFile; 
  12. - (void)updateProgress:(int64_t)receiveDataLength totalDataLength:(int64_t)totalDataLength; 
  13. @end 
  14.   
  15. @implementation AFNetworkingViewController 
  16.   
  17. - (void)viewDidLoad { 
  18.     [super viewDidLoad]; 
  19.       
  20.     [self layoutUI]; 
  21.   
  22. - (void)didReceiveMemoryWarning { 
  23.     [super didReceiveMemoryWarning]; 
  24.     // Dispose of any resources that can be recreated. 
  25.   
  26. - (void)showAlert:(NSString *)msg { 
  27.     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络情况" 
  28.                                                     message:msg 
  29.                                                    delegate:self 
  30.                                           cancelButtonTitle:nil 
  31.                                           otherButtonTitles:@"确定", nil]; 
  32.     [alert show]; 
  33.   
  34. - (void)checkNetwork { 
  35.     NSURL *baseURL = [NSURL URLWithString:@"http://www.baidu.com/"]; 
  36.     AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL]; 
  37.       
  38.     NSOperationQueue *operationQueue = manager.operationQueue; 
  39.     [manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { 
  40.         switch (status) { 
  41.             case AFNetworkReachabilityStatusReachableViaWiFi: 
  42.                 [self showAlert:@"Wi-Fi 网络下"]; 
  43.                 [operationQueue setSuspended:NO]; 
  44.                 break
  45.             case AFNetworkReachabilityStatusReachableViaWWAN: 
  46.                 [self showAlert:@"2G/3G/4G 蜂窝移动网络下"]; 
  47.                 [operationQueue setSuspended:YES]; 
  48.                 break
  49.             case AFNetworkReachabilityStatusNotReachable: 
  50.             default
  51.                 [self showAlert:@"未连接网络"]; 
  52.                 [operationQueue setSuspended:YES]; 
  53.                 break
  54.         } 
  55.     }]; 
  56.       
  57.     [manager.reachabilityManager startMonitoring]; 
  58.   
  59. - (void)layoutUI { 
  60.     self.navigationItem.title = kTitleOfAFNetworking; 
  61.     self.view.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1.000]; 
  62.       
  63.     //条件表达式中,「?:」可以表示在条件不成立的情况,才使用后者赋值,否则使用用于条件判断的前者赋值 
  64.     //以下语句等同于:UIButton *btn = _btnDownloadFileByConnection ? _btnDownloadFileByConnection : [UIButton new]; 
  65.     //在 .NET 中,相当于使用「??」;在 JavaScript 中,相当于使用「||」来实现这种类似的判断 
  66.     UIButton *btn = _btnDownloadFileByConnection ?: [UIButton new]; 
  67.     [btn beautifulButton:nil]; 
  68.     [_btnDownloadFileBySession beautifulButton:[UIColor orangeColor]]; 
  69.       
  70.     //进度效果 
  71.     _hud = [[MBProgressHUD alloc] initWithView:self.view]; 
  72.     _hud.mode = MBProgressHUDModeDeterminate; 
  73.     _hud.labelText = @"下载中..."
  74.     [_hud hide:YES]; 
  75.     [self.view addSubview:_hud]; 
  76.       
  77.     //检查网络情况 
  78.     [self checkNetwork]; 
  79.       
  80.     //启动网络活动指示器;会根据网络交互情况,实时显示或隐藏网络活动指示器;他通过「通知与消息机制」来实现 [UIApplication sharedApplication].networkActivityIndicatorVisible 的控制 
  81.     [AFNetworkActivityIndicatorManager sharedManager].enabled = YES; 
  82.   
  83. - (NSMutableURLRequest *)downloadRequest { 
  84.     NSString *fileURLStr = kFileURLStr; 
  85.     //编码操作;对应的解码操作是用 stringByRemovingPercentEncoding 方法 
  86.     fileURLStr = [fileURLStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 
  87.     NSURL *fileURL = [NSURL URLWithString:fileURLStr]; 
  88.       
  89.     //创建请求 
  90.     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:fileURL]; 
  91.     return request; 
  92.   
  93. - (NSURL *)saveURL:(NSURLResponse *)response deleteExistFile:(BOOL)deleteExistFile { 
  94.     NSString *fileName = response ? [response suggestedFilename] : _lblFileName.text; 
  95.       
  96.     //方法一 
  97. //    NSString *savePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; 
  98. //    savePath = [savePath stringByAppendingPathComponent:fileName]; 
  99. //    NSURL *saveURL = [NSURL fileURLWithPath:savePath]; 
  100.       
  101.     //方法二 
  102.     NSURL *saveURL = [[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil]; 
  103.     saveURL = [saveURL URLByAppendingPathComponent:fileName]; 
  104.     NSString *savePath = [saveURL path]; 
  105.       
  106.     if (deleteExistFile) { 
  107.         NSError *saveError; 
  108.         NSFileManager *fileManager = [NSFileManager defaultManager]; 
  109.         //判断是否存在旧的目标文件,如果存在就先移除;避免无法复制问题 
  110.         if ([fileManager fileExistsAtPath:savePath]) { 
  111.             [fileManager removeItemAtPath:savePath error:&saveError]; 
  112.             if (saveError) { 
  113.                 NSLog(@"移除旧的目标文件失败,错误信息:%@", saveError.localizedDescription); 
  114.             } 
  115.         } 
  116.     } 
  117.       
  118.     return saveURL; 
  119.   
  120. - (void)updateProgress:(int64_t)receiveDataLength totalDataLength:(int64_t)totalDataLength; { 
  121.     dispatch_async(dispatch_get_main_queue(), ^{ //使用主队列异步方式(主线程)执行更新 UI 操作 
  122.         _hud.progress = (float)receiveDataLength / totalDataLength; 
  123.           
  124.         if (receiveDataLength == totalDataLength) { 
  125.             _lblMessage.text =  receiveDataLength < 0 ? @"下载失败" : @"下载完成"
  126.             //kApplication.networkActivityIndicatorVisible = NO; 
  127.             [_hud hide:YES]; 
  128.         } else { 
  129.             _lblMessage.text = @"下载中..."
  130.             //kApplication.networkActivityIndicatorVisible = YES; 
  131.             [_hud show:YES]; 
  132.         } 
  133.     }); 
  134.   
  135. - (IBAction)downloadFileByConnection:(id)sender { 
  136.     //创建请求 
  137.     NSMutableURLRequest *request = [self downloadRequest]; 
  138.       
  139.     //创建请求操作 
  140.     AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 
  141.     NSString *savePath = [[self saveURL:nil deleteExistFile:NO] path]; 
  142.       
  143.     [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) { 
  144.         NSLog(@"已经接收到响应数据,数据长度为%lld字节...", totalBytesRead); 
  145.           
  146.         [self updateProgress:totalBytesRead totalDataLength:totalBytesExpectedToRead]; 
  147.     }]; 
  148.       
  149.     [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 
  150.         NSLog(@"已经接收完所有响应数据"); 
  151.           
  152.         NSData *data = (NSData *)responseObject; 
  153.         [data writeToFile:savePath atomically:YES]; //responseObject 的对象类型是 NSData 
  154.           
  155.         [self updateProgress:100 totalDataLength:100]; 
  156.     } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
  157.         NSLog(@"下载失败,错误信息:%@", error.localizedDescription); 
  158.           
  159.         [self updateProgress:-1 totalDataLength:-1]; 
  160.     }]; 
  161.       
  162.     //启动请求操作 
  163.     [operation start]; 
  164.   
  165. - (IBAction)downloadFileBySession:(id)sender { 
  166.     //创建请求 
  167.     NSMutableURLRequest *request = [self downloadRequest]; 
  168.       
  169.     //创建会话配置「进程内会话」 
  170.     NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration]; 
  171.     sessionConfiguration.timeoutIntervalForRequest = 60.0//请求超时时间;默认为60秒 
  172.     sessionConfiguration.allowsCellularAccess = YES; //是否允许蜂窝网络访问(2G/3G/4G) 
  173.     sessionConfiguration.HTTPMaximumConnectionsPerHost = 4//限制每次最多连接数;在 iOS 中默认值为4 
  174.       
  175.     //创建会话管理器 
  176.     AFURLSessionManager *sessionManager = [[AFURLSessionManager alloc] initWithSessionConfiguration:sessionConfiguration]; 
  177.       
  178.     //创建会话下载任务,并且启动他;在非主线程中执行 
  179.     NSURLSessionDownloadTask *task = [sessionManager 
  180.                                       downloadTaskWithRequest:request 
  181.                                       progress:nil 
  182.                                       destination:^ NSURL*(NSURL *targetPath, NSURLResponse *response) { 
  183.                                           //当 sessionManager 调用 setDownloadTaskDidFinishDownloadingBlock: 方法,并且方法代码块返回值不为 nil 时(优先级高),下面的两句代码是不执行的(优先级低) 
  184.                                           NSLog(@"下载后的临时保存路径:%@", targetPath); 
  185.                                           return [self saveURL:response deleteExistFile:YES]; 
  186.                                       } completionHandler:^ (NSURLResponse *response, NSURL *filePath, NSError *error) { 
  187.                                           if (!error) { 
  188.                                               NSLog(@"下载后的保存路径:%@", filePath); //为上面代码块返回的路径 
  189.                                                 
  190.                                               [self updateProgress:100 totalDataLength:100]; 
  191.                                           } else { 
  192.                                               NSLog(@"下载失败,错误信息:%@", error.localizedDescription); 
  193.                                                 
  194.                                               [self updateProgress:-1 totalDataLength:-1]; 
  195.                                           } 
  196.                                             
  197.                                           [_hud hide:YES]; 
  198.                                       }]; 
  199.       
  200.     //类似 NSURLSessionDownloadDelegate 的方法操作 
  201.     //- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite; 
  202.     [sessionManager setDownloadTaskDidWriteDataBlock:^ (NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) { 
  203.         NSLog(@"已经接收到响应数据,数据长度为%lld字节...", totalBytesWritten); 
  204.           
  205.         [self updateProgress:totalBytesWritten totalDataLength:totalBytesExpectedToWrite]; 
  206.     }]; 
  207.       
  208.     //- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location; 
  209.     [sessionManager setDownloadTaskDidFinishDownloadingBlock:^ NSURL*(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location) { 
  210.         NSLog(@"已经接收完所有响应数据,下载后的临时保存路径:%@", location); 
  211.         return [self saveURL:nil deleteExistFile:YES]; 
  212.     }]; 
  213.       
  214.     [task resume]; 
  215.   
  216. @end 

AFNetworkingViewController.xib

 
  1. [?xml version="1.0" encoding="UTF-8" standalone="no"?] 
  2. [document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="7706" systemVersion="14E46" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES"
  3.     [dependencies] 
  4.         [deployment identifier="iOS"/] 
  5.         [plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="7703"/] 
  6.     [/dependencies] 
  7.     [objects] 
  8.         [placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner" customClass="AFNetworkingViewController"
  9.             [connections] 
  10.                 [outlet property="btnDownloadFileByConnection" destination="IkH-un-SOz" id="gDd-6X-uxU"/] 
  11.                 [outlet property="btnDownloadFileBySession" destination="mwt-p9-tRE" id="5Qk-Zm-V3w"/] 
  12.                 [outlet property="lblFileName" destination="dlB-Qn-eOO" id="NdS-9n-7KX"/] 
  13.                 [outlet property="lblMessage" destination="qlQ-nM-BXU" id="tRe-SR-AQE"/] 
  14.                 [outlet property="view" destination="i5M-Pr-FkT" id="sfx-zR-JGt"/] 
  15.             [/connections] 
  16.         [/placeholder] 
  17.         [placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/] 
  18.         [view clearsContextBeforeDrawing="NO" contentMode="scaleToFill" id="i5M-Pr-FkT"
  19.             [rect key="frame" x="0.0" y="0.0" width="600" height="600"/] 
  20.             [autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/] 
  21.             [subviews] 
  22.                 [label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="metro_demo使用Highcharts实现图表展示.zip" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="dlB-Qn-eOO"
  23.                     [rect key="frame" x="145" y="104" width="309.5" height="18"/] 
  24.                     [fontDescription key="fontDescription" type="boldSystem" pointSize="15"/] 
  25.                     [color key="textColor" cocoaTouchSystemColor="darkTextColor"/] 
  26.                     [nil key="highlightedColor"/] 
  27.                 [/label] 
  28.                 [button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="mwt-p9-tRE"
  29.                     [rect key="frame" x="175" y="520" width="250" height="40"/] 
  30.                     [constraints] 
  31.                         [constraint firstAttribute="width" constant="250" id="I5D-tA-ffH"/] 
  32.                         [constraint firstAttribute="height" constant="40" id="Y8C-D4-IVr"/] 
  33.                     [/constraints] 
  34.                     [state key="normal" title="基于 NSURLSession 的下载"
  35.                         [color key="titleShadowColor" white="0.5" alpha="1" colorSpace="calibratedWhite"/] 
  36.                     [/state] 
  37.                     [connections] 
  38.                         [action selector="downloadFileBySession:" destination="-1" eventType="touchUpInside" id="z6s-cq-dag"/] 
  39.                     [/connections] 
  40.                 [/button] 
  41.                 [label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Label" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="qlQ-nM-BXU"
  42.                     [rect key="frame" x="145" y="140" width="37.5" height="18"/] 
  43.                     [fontDescription key="fontDescription" type="system" pointSize="15"/] 
  44.                     [color key="textColor" red="0.0" green="0.50196081399917603" blue="1" alpha="1" colorSpace="calibratedRGB"/] 
  45.                     [nil key="highlightedColor"/] 
  46.                     [userDefinedRuntimeAttributes] 
  47.                         [userDefinedRuntimeAttribute type="string" keyPath="text" value=""/] 
  48.                     [/userDefinedRuntimeAttributes] 
  49.                 [/label] 
  50.                 [button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="IkH-un-SOz"
  51.                     [rect key="frame" x="174" y="460" width="250" height="40"/] 
  52.                     [constraints] 
  53.                         [constraint firstAttribute="width" constant="250" id="3a7-Og-iWa"/] 
  54.                         [constraint firstAttribute="height" constant="40" id="mc0-yK-hWE"/] 
  55.                     [/constraints] 
  56.                     [state key="normal" title="基于 NSURLConnection 的下载"
  57.                         [color key="titleShadowColor" white="0.5" alpha="1" colorSpace="calibratedWhite"/] 
  58.                     [/state] 
  59.                     [connections] 
  60.                         [action selector="downloadFileByConnection:" destination="-1" eventType="touchUpInside" id="1ko-jP-kCo"/] 
  61.                     [/connections] 
  62.                 [/button] 
  63.             [/subviews] 
  64.             [color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/] 
  65.             [constraints] 
  66.                 [constraint firstItem="mwt-p9-tRE" firstAttribute="top" secondItem="IkH-un-SOz" secondAttribute="bottom" constant="20" id="Sye-JW-gux"/] 
  67.                 [constraint firstAttribute="centerX" secondItem="dlB-Qn-eOO" secondAttribute="centerX" id="gNK-NO-rth"/] 
  68.                 [constraint firstItem="dlB-Qn-eOO" firstAttribute="top" secondItem="i5M-Pr-FkT" secondAttribute="top" constant="104" id="hwU-O2-Fed"/] 
  69.                 [constraint firstAttribute="centerX" secondItem="IkH-un-SOz" secondAttribute="centerX" constant="1" id="lF1-Yf-Axs"/] 
  70.                 [constraint firstAttribute="centerX" secondItem="mwt-p9-tRE" secondAttribute="centerX" id="teN-3t-8Gc"/] 
  71.                 [constraint firstItem="qlQ-nM-BXU" firstAttribute="top" secondItem="i5M-Pr-FkT" secondAttribute="top" constant="140" id="w3g-ej-P18"/] 
  72.                 [constraint firstItem="dlB-Qn-eOO" firstAttribute="leading" secondItem="qlQ-nM-BXU" secondAttribute="leading" constant="0.5" id="wMU-pU-z9f"/] 
  73.                 [constraint firstAttribute="bottom" secondItem="mwt-p9-tRE" secondAttribute="bottom" constant="40" id="yBq-He-Jv8"/] 
  74.             [/constraints] 
  75.         [/view] 
  76.     [/objects] 
  77. [/document] 
  78.   
  79. View Cod 

AppDelegate.h

 
  1. #import @interface AppDelegate : UIResponder @property (strong, nonatomic) UIWindow *window; 
  2. @property (strong, nonatomic) UINavigationController *navigationController; 
  3.   
  4. @end 

AppDelegate.m

  1. #import "AppDelegate.h" 
  2. #import "ViewController.h" 
  3.   
  4. @interface AppDelegate () 
  5.   
  6. @end 
  7.   
  8. @implementation AppDelegate 
  9.   
  10.   
  11. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 
  12.     _window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; 
  13.     ViewController *viewController = [[ViewController alloc] 
  14.                                       initWithSampleNameArray:@[ kTitleOfNSURLConnection, 
  15.                                                                  kTitleOfNSURLConnectionDelegate, 
  16.                                                                  kTitleOfNSURLSession, 
  17.                                                                  kTitleOfNSURLSessionDelegate, 
  18.                                                                  kTitleOfAFNetworking]]; 
  19.     _navigationController = [[UINavigationController alloc] initWithRootViewController:viewController]; 
  20.     _window.rootViewController = _navigationController; 
  21.     //[_window addSubview:_navigationController.view]; //当_window.rootViewController关联时,这一句可有可无 
  22.     [_window makeKeyAndVisible]; 
  23.     return YES; 
  24.   
  25. - (void)applicationWillResignActive:(UIApplication *)application { 
  26.   
  27. - (void)applicationDidEnterBackground:(UIApplication *)application { 
  28.   
  29. - (void)applicationWillEnterForeground:(UIApplication *)application { 
  30.   
  31. - (void)applicationDidBecomeActive:(UIApplication *)application { 
  32.   
  33. - (void)applicationWillTerminate:(UIApplication *)application { 
  34.   
  35. @end 
 
责任编辑:倪明 来源: KenmuHuang的博客
相关推荐

2015-01-05 09:15:39

2010-07-22 12:19:07

2009-07-06 16:18:51

Servlet下载文件

2015-04-13 00:24:17

2017-01-16 14:13:37

分布式数据库

2018-04-03 16:24:34

分布式方式

2023-08-01 14:07:05

模型AI

2017-03-09 15:12:50

2015-11-06 16:54:56

歪评寒冬程序员

2013-05-20 08:59:24

2020-02-16 11:13:39

远程办公工具技术

2020-09-22 09:41:09

前端

2015-01-19 09:11:31

2024-10-18 08:00:00

SpringBoot框架开发

2021-06-06 12:59:14

实现方式计数

2011-06-12 21:25:01

51CTO一周要闻分析

2014-04-14 14:02:27

2014-01-07 14:59:21

2016-01-22 16:53:32

云计算云应用云趋势

2013-12-10 09:15:46

FedoraFedora 20
点赞
收藏

51CTO技术栈公众号