(1)使用 NSURLConnection 直接方式
(2)使用 NSURLConnection 代理方式
(3)使用 NSURLSession 直接方式
(4)使用 NSURLSession 代理方式
(5)使用 AFNetworking 方式
附加功能:
(1)使用 AFNetworking 中的 AFNetworkReachabilityManager 來檢查網絡情況:
AFNetworkReachabilityStatusReachableViaWiFi:Wi-Fi 網絡下
AFNetworkReachabilityStatusReachableViaWWAN:2G/3G/4G 蜂窩移動網絡下
AFNetworkReachabilityStatusNotReachable:未連接網絡
(2)使用 AFNetworking 中的 AFNetworkActivityIndicatorManager 來啟動網絡活動指示器:
#import "AFNetworkActivityIndicatorManager.h" //啟動網絡活動指示器;會根據網絡交互情況,實時顯示或隱藏網絡活動指示器;他通過「通知與消息機制」來實現 [UIApplication sharedApplication].networkActivityIndicatorVisible 的控制 [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
效果如下:
ViewController.h
#import @interface ViewController : UITableViewController @property (copy, nonatomic) NSArray *arrSampleName; - (instancetype)initWithSampleNameArray:(NSArray *)arrSampleName; @end
ViewController.m
#import "ViewController.h" #import "NSURLConnectionViewController.h" #import "NSURLConnectionDelegateViewController.h" #import "NSURLSessionViewController.h" #import "NSURLSessionDelegateViewController.h" #import "AFNetworkingViewController.h" @interface ViewController () - (void)layoutUI; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self layoutUI]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (instancetype)initWithSampleNameArray:(NSArray *)arrSampleName { if (self = [super initWithStyle:UITableViewStyleGrouped]) { self.navigationItem.title = @"多種方式實現文件下載功能"; self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:nil action:nil]; _arrSampleName = arrSampleName; } return self; } - (void)layoutUI { } #pragma mark - UITableViewController相關方法重寫 - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section { return 0.1; } - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [_arrSampleName count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *cellIdentifier = @"cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; if (!cell) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; } cell.textLabel.text = _arrSampleName[indexPath.row]; return cell; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { switch (indexPath.row) { case 0: { NSURLConnectionViewController *connectionVC = [NSURLConnectionViewController new]; [self.navigationController pushViewController:connectionVC animated:YES]; break; } case 1: { NSURLConnectionDelegateViewController *connectionDelegateVC = [NSURLConnectionDelegateViewController new]; [self.navigationController pushViewController:connectionDelegateVC animated:YES]; break; } case 2: { NSURLSessionViewController *sessionVC = [NSURLSessionViewController new]; [self.navigationController pushViewController:sessionVC animated:YES]; break; } case 3: { NSURLSessionDelegateViewController *sessionDelegateVC = [NSURLSessionDelegateViewController new]; [self.navigationController pushViewController:sessionDelegateVC animated:YES]; break; } case 4: { AFNetworkingViewController *networkingVC = [AFNetworkingViewController new]; [self.navigationController pushViewController:networkingVC animated:YES]; break; } default: break; } } @end
PrefixHeader.pch
#define kFileURLStr @"http://files.cnblogs.com/files/huangjianwu/metro_demo使用Highcharts實現圖表展示.zip" #define kTitleOfNSURLConnection @"使用 NSURLConnection 直接方式" #define kTitleOfNSURLConnectionDelegate @"使用 NSURLConnection 代理方式" #define kTitleOfNSURLSession @"使用 NSURLSession 直接方式" #define kTitleOfNSURLSessionDelegate @"使用 NSURLSession 代理方式" #define kTitleOfAFNetworking @"使用 AFNetworking 方式" #define kApplication [UIApplication sharedApplication]
UIButton+BeautifulButton.h
#import @interface UIButton (BeautifulButton) /** * 根據按鈕文字顏色,返回對應文字顏色的圓角按鈕 * * @param tintColor 按鈕文字顏色;nil 的話就為深灰色 */ - (void)beautifulButton:(UIColor *)tintColor; @end
UIButton+BeautifulButton.m
#import "UIButton+BeautifulButton.h" @implementation UIButton (BeautifulButton) - (void)beautifulButton:(UIColor *)tintColor { self.tintColor = tintColor ?: [UIColor darkGrayColor]; self.layer.masksToBounds = YES; self.layer.cornerRadius = 10.0; self.layer.borderColor = [UIColor grayColor].CGColor; self.layer.borderWidth = 1.0; } @end
NSURLConnectionViewController.h
#import @interface NSURLConnectionViewController : UIViewController @property (strong, nonatomic) IBOutlet UILabel *lblFileName; @property (strong, nonatomic) IBOutlet UILabel *lblMessage; @property (strong, nonatomic) IBOutlet UIButton *btnDownloadFile; @end
NSURLConnectionViewController.m
#import "NSURLConnectionViewController.h" #import "UIButton+BeautifulButton.h" @interface NSURLConnectionViewController () - (void)layoutUI; - (void)saveDataToDisk:(NSData *)data; @end @implementation NSURLConnectionViewController - (void)viewDidLoad { [super viewDidLoad]; [self layoutUI]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (void)layoutUI { self.navigationItem.title = kTitleOfNSURLConnection; self.view.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1.000]; [_btnDownloadFile beautifulButton:nil]; } - (void)saveDataToDisk:(NSData *)data { //數據接收完保存文件;注意蘋果官方要求:下載數據只能保存在緩存目錄(/Library/Caches) NSString *savePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; savePath = [savePath stringByAppendingPathComponent:_lblFileName.text]; [data writeToFile:savePath atomically:YES]; //writeToFile: 方法:如果 savePath 文件存在,他會執行覆蓋 } - (IBAction)downloadFile:(id)sender { _lblMessage.text = @"下載中..."; NSString *fileURLStr = kFileURLStr; //編碼操作;對應的解碼操作是用 stringByRemovingPercentEncoding 方法 fileURLStr = [fileURLStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *fileURL = [NSURL URLWithString:fileURLStr]; //創建請求 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:fileURL]; //創建連接;Apple 提供的處理一般請求的兩種方法,他們不需要進行一系列的 NSURLConnectionDataDelegate 委托協議方法操作,簡潔直觀 //方法一:發送一個同步請求;不建議使用,因為當前線程是主線程的話,會造成線程阻塞,一般比較少用 // NSURLResponse *response; // NSError *connectionError; // NSData *data = [NSURLConnection sendSynchronousRequest:request // returningResponse:&response // error:&connectionError]; // if (!connectionError) { // [self saveDataToDisk:data]; // NSLog(@"保存成功"); // // _lblMessage.text = @"下載完成"; // } else { // NSLog(@"下載失敗,錯誤信息:%@", connectionError.localizedDescription); // // _lblMessage.text = @"下載失敗"; // } //方法二:發送一個異步請求 [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { if (!connectionError) { [self saveDataToDisk:data]; NSLog(@"保存成功"); _lblMessage.text = @"下載完成"; } else { NSLog(@"下載失敗,錯誤信息:%@", connectionError.localizedDescription); _lblMessage.text = @"下載失敗"; } }]; } @end
NSURLConnectionViewController.xib
[?xml version="1.0" encoding="UTF-8" standalone="no"?] [document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="6211" systemVersion="14A298i" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES"] [dependencies] [plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="6204"/] [/dependencies] [objects] [placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner" customClass="NSURLConnectionViewController"] [connections] [outlet property="btnDownloadFile" destination="mwt-p9-tRE" id="ZVc-6S-ES3"/] [outlet property="lblFileName" destination="dlB-Qn-eOO" id="NdS-9n-7KX"/] [outlet property="lblMessage" destination="qlQ-nM-BXU" id="tRe-SR-AQE"/] [outlet property="view" destination="i5M-Pr-FkT" id="sfx-zR-JGt"/] [/connections] [/placeholder] [placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/] [view clearsContextBeforeDrawing="NO" contentMode="scaleToFill" id="i5M-Pr-FkT"] [rect key="frame" x="0.0" y="0.0" width="600" height="600"/] [autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/] [subviews] [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"] [rect key="frame" x="145" y="104" width="309.5" height="18"/] [fontDescription key="fontDescription" type="boldSystem" pointSize="15"/] [color key="textColor" cocoaTouchSystemColor="darkTextColor"/] [nil key="highlightedColor"/] [/label] [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"] [rect key="frame" x="145" y="140" width="37.5" height="18"/] [fontDescription key="fontDescription" type="system" pointSize="15"/] [color key="textColor" red="0.0" green="0.50196081399917603" blue="1" alpha="1" colorSpace="calibratedRGB"/] [nil key="highlightedColor"/] [userDefinedRuntimeAttributes] [userDefinedRuntimeAttribute type="string" keyPath="text" value=""/] [/userDefinedRuntimeAttributes] [/label] [/subviews] [color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/] [constraints] [constraint firstAttribute="centerX" secondItem="dlB-Qn-eOO" secondAttribute="centerX" id="gNK-NO-rth"/] [constraint firstItem="dlB-Qn-eOO" firstAttribute="top" secondItem="i5M-Pr-FkT" secondAttribute="top" constant="104" id="hwU-O2-Fed"/] [constraint firstAttribute="centerX" secondItem="mwt-p9-tRE" secondAttribute="centerX" id="teN-3t-8Gc"/] [constraint firstItem="qlQ-nM-BXU" firstAttribute="top" secondItem="i5M-Pr-FkT" secondAttribute="top" constant="140" id="w3g-ej-P18"/] [constraint firstItem="dlB-Qn-eOO" firstAttribute="leading" secondItem="qlQ-nM-BXU" secondAttribute="leading" constant="0.5" id="wMU-pU-z9f"/] [constraint firstAttribute="bottom" secondItem="mwt-p9-tRE" secondAttribute="bottom" constant="40" id="yBq-He-Jv8"/] [/constraints] [/view] [/objects] [/document]
NSURLConnectionDelegateViewController.h
#import @interface NSURLConnectionDelegateViewController : UIViewController @property (strong, nonatomic) NSMutableData *mDataReceive; @property (assign, nonatomic) NSUInteger totalDataLength; @property (strong, nonatomic) IBOutlet UILabel *lblFileName; @property (strong, nonatomic) IBOutlet UIProgressView *progVDownloadFile; @property (strong, nonatomic) IBOutlet UILabel *lblMessage; @property (strong, nonatomic) IBOutlet UIButton *btnDownloadFile; @end
NSURLConnectionDelegateViewController.m
#import @interface ViewController : UITableViewController @property (copy, nonatomic) NSArray *arrSampleName; - (instancetype)initWithSampleNameArray:(NSArray *)arrSampleName; @end
0
NSURLConnectionDelegateViewController.xib
#import @interface ViewController : UITableViewController @property (copy, nonatomic) NSArray *arrSampleName; - (instancetype)initWithSampleNameArray:(NSArray *)arrSampleName; @end
1
NSURLSessionViewController.h
#import @interface ViewController : UITableViewController @property (copy, nonatomic) NSArray *arrSampleName; - (instancetype)initWithSampleNameArray:(NSArray *)arrSampleName; @end
2
NSURLSessionViewController.m
#import @interface ViewController : UITableViewController @property (copy, nonatomic) NSArray *arrSampleName; - (instancetype)initWithSampleNameArray:(NSArray *)arrSampleName; @end
3
NSURLSessionViewController.xib
#import @interface ViewController : UITableViewController @property (copy, nonatomic) NSArray *arrSampleName; - (instancetype)initWithSampleNameArray:(NSArray *)arrSampleName; @end
4
NSURLSessionDelegateViewController.h
#import @interface ViewController : UITableViewController @property (copy, nonatomic) NSArray *arrSampleName; - (instancetype)initWithSampleNameArray:(NSArray *)arrSampleName; @end
5
NSURLSessionDelegateViewController.m
#import @interface ViewController : UITableViewController @property (copy, nonatomic) NSArray *arrSampleName; - (instancetype)initWithSampleNameArray:(NSArray *)arrSampleName; @end
6
NSURLSessionDelegateViewController.xib
#import @interface ViewController : UITableViewController @property (copy, nonatomic) NSArray *arrSampleName; - (instancetype)initWithSampleNameArray:(NSArray *)arrSampleName; @end
7
AFNetworkingViewController.h
#import @interface ViewController : UITableViewController @property (copy, nonatomic) NSArray *arrSampleName; - (instancetype)initWithSampleNameArray:(NSArray *)arrSampleName; @end
8
AFNetworkingViewController.m
#import @interface ViewController : UITableViewController @property (copy, nonatomic) NSArray *arrSampleName; - (instancetype)initWithSampleNameArray:(NSArray *)arrSampleName; @end
9
AFNetworkingViewController.xib
#import "ViewController.h" #import "NSURLConnectionViewController.h" #import "NSURLConnectionDelegateViewController.h" #import "NSURLSessionViewController.h" #import "NSURLSessionDelegateViewController.h" #import "AFNetworkingViewController.h" @interface ViewController () - (void)layoutUI; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self layoutUI]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (instancetype)initWithSampleNameArray:(NSArray *)arrSampleName { if (self = [super initWithStyle:UITableViewStyleGrouped]) { self.navigationItem.title = @"多種方式實現文件下載功能"; self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:nil action:nil]; _arrSampleName = arrSampleName; } return self; } - (void)layoutUI { } #pragma mark - UITableViewController相關方法重寫 - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section { return 0.1; } - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [_arrSampleName count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *cellIdentifier = @"cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; if (!cell) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; } cell.textLabel.text = _arrSampleName[indexPath.row]; return cell; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { switch (indexPath.row) { case 0: { NSURLConnectionViewController *connectionVC = [NSURLConnectionViewController new]; [self.navigationController pushViewController:connectionVC animated:YES]; break; } case 1: { NSURLConnectionDelegateViewController *connectionDelegateVC = [NSURLConnectionDelegateViewController new]; [self.navigationController pushViewController:connectionDelegateVC animated:YES]; break; } case 2: { NSURLSessionViewController *sessionVC = [NSURLSessionViewController new]; [self.navigationController pushViewController:sessionVC animated:YES]; break; } case 3: { NSURLSessionDelegateViewController *sessionDelegateVC = [NSURLSessionDelegateViewController new]; [self.navigationController pushViewController:sessionDelegateVC animated:YES]; break; } case 4: { AFNetworkingViewController *networkingVC = [AFNetworkingViewController new]; [self.navigationController pushViewController:networkingVC animated:YES]; break; } default: break; } } @end
0
AppDelegate.h
#import "ViewController.h" #import "NSURLConnectionViewController.h" #import "NSURLConnectionDelegateViewController.h" #import "NSURLSessionViewController.h" #import "NSURLSessionDelegateViewController.h" #import "AFNetworkingViewController.h" @interface ViewController () - (void)layoutUI; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self layoutUI]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (instancetype)initWithSampleNameArray:(NSArray *)arrSampleName { if (self = [super initWithStyle:UITableViewStyleGrouped]) { self.navigationItem.title = @"多種方式實現文件下載功能"; self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:nil action:nil]; _arrSampleName = arrSampleName; } return self; } - (void)layoutUI { } #pragma mark - UITableViewController相關方法重寫 - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section { return 0.1; } - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [_arrSampleName count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *cellIdentifier = @"cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; if (!cell) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; } cell.textLabel.text = _arrSampleName[indexPath.row]; return cell; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { switch (indexPath.row) { case 0: { NSURLConnectionViewController *connectionVC = [NSURLConnectionViewController new]; [self.navigationController pushViewController:connectionVC animated:YES]; break; } case 1: { NSURLConnectionDelegateViewController *connectionDelegateVC = [NSURLConnectionDelegateViewController new]; [self.navigationController pushViewController:connectionDelegateVC animated:YES]; break; } case 2: { NSURLSessionViewController *sessionVC = [NSURLSessionViewController new]; [self.navigationController pushViewController:sessionVC animated:YES]; break; } case 3: { NSURLSessionDelegateViewController *sessionDelegateVC = [NSURLSessionDelegateViewController new]; [self.navigationController pushViewController:sessionDelegateVC animated:YES]; break; } case 4: { AFNetworkingViewController *networkingVC = [AFNetworkingViewController new]; [self.navigationController pushViewController:networkingVC animated:YES]; break; } default: break; } } @end
1
AppDelegate.m
#import "ViewController.h" #import "NSURLConnectionViewController.h" #import "NSURLConnectionDelegateViewController.h" #import "NSURLSessionViewController.h" #import "NSURLSessionDelegateViewController.h" #import "AFNetworkingViewController.h" @interface ViewController () - (void)layoutUI; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self layoutUI]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (instancetype)initWithSampleNameArray:(NSArray *)arrSampleName { if (self = [super initWithStyle:UITableViewStyleGrouped]) { self.navigationItem.title = @"多種方式實現文件下載功能"; self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:nil action:nil]; _arrSampleName = arrSampleName; } return self; } - (void)layoutUI { } #pragma mark - UITableViewController相關方法重寫 - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section { return 0.1; } - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [_arrSampleName count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *cellIdentifier = @"cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; if (!cell) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; } cell.textLabel.text = _arrSampleName[indexPath.row]; return cell; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { switch (indexPath.row) { case 0: { NSURLConnectionViewController *connectionVC = [NSURLConnectionViewController new]; [self.navigationController pushViewController:connectionVC animated:YES]; break; } case 1: { NSURLConnectionDelegateViewController *connectionDelegateVC = [NSURLConnectionDelegateViewController new]; [self.navigationController pushViewController:connectionDelegateVC animated:YES]; break; } case 2: { NSURLSessionViewController *sessionVC = [NSURLSessionViewController new]; [self.navigationController pushViewController:sessionVC animated:YES]; break; } case 3: { NSURLSessionDelegateViewController *sessionDelegateVC = [NSURLSessionDelegateViewController new]; [self.navigationController pushViewController:sessionDelegateVC animated:YES]; break; } case 4: { AFNetworkingViewController *networkingVC = [AFNetworkingViewController new]; [self.navigationController pushViewController:networkingVC animated:YES]; break; } default: break; } } @end
2