多种方式实现文件下载功能

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

(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"23//启动网络活动指示器;会根据网络交互情况,实时显示或隐藏网络活动指示器;他通过「通知与消息机制」来实现 [UIapplicationsharedApplication].networkActivityIndicatorVisible 的控制4[AFNetworkActivityIndicatorManager sharedManager].enabled = YES;

效果如下:

ViewController.h

1#import<UIKit/UIKit.h>23@interfaceViewController : UITableViewController4@PRoperty (copy, nonatomic) NSArray *arrSampleName;56- (instancetype)initWithSampleNameArray:(NSArray *)arrSampleName;78@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"78@interfaceViewController ()9- (void)layoutUI;10@end1112@implementationViewController13- (void)viewDidLoad {14[super viewDidLoad];1516[self layoutUI];17}1819- (void)didReceiveMemoryWarning {20[super didReceiveMemoryWarning];21//Dispose of any resources that can be recreated.22}2324- (instancetype)initWithSampleNameArray:(NSArray *)arrSampleName {25if(self =[super initWithStyle:UITableViewStyleGrouped]) {26self.navigationItem.title =@"多种方式实现文件下载功能";27self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回"style:UIBarButtonItemStylePlain target:nil action:nil];2829_arrSampleName =arrSampleName;30}31returnself;32}3334- (void)layoutUI {35}3637#pragmamark - UITableViewController相关方法重写38- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {39return0.1;40}4142- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {43return1;44}4546- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {47return[_arrSampleName count];48}4950- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {51staticNSString *cellIdentifier =@"cell";52UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:cellIdentifier];53if(!cell) {54cell =[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];55}56cell.textLabel.text =_arrSampleName[indexPath.row];57returncell;58}5960- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {61switch(indexPath.row) {62case0: {63NSURLConnectionViewController *connectionVC = [NSURLConnectionViewControllernew];64[self.navigationController pushViewController:connectionVC animated:YES];65

break;66}67case1: {68NSURLConnectionDelegateViewController *connectionDelegateVC = [NSURLConnectionDelegateViewControllernew];69[self.navigationController pushViewController:connectionDelegateVC animated:YES];70

break;71}72case2: {73NSURLSessionViewController *sessionVC = [NSURLSessionViewControllernew];74[self.navigationController pushViewController:sessionVC animated:YES];75

break;76}77case3: {78NSURLSessionDelegateViewController *sessionDelegateVC = [NSURLSessionDelegateViewControllernew];79[self.navigationController pushViewController:sessionDelegateVC animated:YES];80

break;81}82case4: {83AFNetworkingViewController *networkingVC = [AFNetworkingViewControllernew];84[self.navigationController pushViewController:networkingVC animated:YES];85

break;86}87default:88

break;89}90}9192@end

PrefixHeader.pch

1#definekFileURLStr @"http://files.cnblogs.com/files/huangjianwu/metro_demo使用Highcharts实现图表展示.zip"23#definekTitleOfNSURLConnection @"使用 NSURLConnection 直接方式"4#definekTitleOfNSURLConnectionDelegate @"使用 NSURLConnection 代理方式"5#definekTitleOfNSURLSession @"使用 NSURLSession 直接方式"6#definekTitleOfNSURLSessionDelegate @"使用 NSURLSession 代理方式"7#definekTitleOfAFNetworking @"使用 AFNetworking 方式"89#definekApplication [UIApplication sharedApplication]

UIButton+BeautifulButton.h

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

UIButton+BeautifulButton.m

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

NSURLConnectionViewController.h

1#import<UIKit/UIKit.h>23@interfaceNSURLConnectionViewController : UIViewController4@property (strong, nonatomic) IBOutlet UILabel *lblFileName;5@property (strong, nonatomic) IBOutlet UILabel *lblMessage;6@property (strong, nonatomic) IBOutlet UIButton *btnDownloadFile;78@end

NSURLConnectionViewController.m

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

NSURLConnectionViewController.xib

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

View Code

NSURLConnectionDelegateViewController.h

1#import<UIKit/UIKit.h>23@interfaceNSURLConnectionDelegateViewController : UIViewController4@property (strong, nonatomic) NSMutableData *mDataReceive;5@property (assign, nonatomic) NSUInteger totalDataLength;67@property (strong, nonatomic) IBOutlet UILabel *lblFileName;8@property (strong, nonatomic) IBOutlet UIProgressView *progVDownloadFile;9@property (strong, nonatomic) IBOutlet UILabel *lblMessage;10@property (strong, nonatomic) IBOutlet UIButton *btnDownloadFile;1112@end

NSURLConnectionDelegateViewController.m

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

NSURLConnectionDelegateViewController.xib

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

View Code

NSURLSessionViewController.h

1#import<UIKit/UIKit.h>23@interfaceNSURLSessionViewController : UIViewController4@property (strong, nonatomic) IBOutlet UILabel *lblFileName;5@property (strong, nonatomic) IBOutlet UILabel *lblMessage;6@property (strong, nonatomic) IBOutlet UIButton *btnDownloadFile;78@end

NSURLSessionViewController.m

1#import"NSURLSessionViewController.h"2#import"UIButton+BeautifulButton.h"34@interfaceNSURLSessionViewController ()5- (void)layoutUI;6@end78@implementationNSURLSessionViewController910- (void)viewDidLoad {11[super viewDidLoad];1213[self layoutUI];14}1516- (void)didReceiveMemoryWarning {17[super didReceiveMemoryWarning];18//Dispose of any resources that can be recreated.19}2021- (void)layoutUI {22self.navigationItem.title =kTitleOfNSURLSession;23self.view.backgroundColor = [UIColor colorWithWhite:0.95alpha:1.000];2425[_btnDownloadFile beautifulButton:nil];26}2728- (IBAction)downloadFile:(id)sender {29_lblMessage.text =@"下载中...";3031NSString *fileURLStr =kFileURLStr;32//编码操作;对应的解码操作是用 stringByRemovingPercentEncoding 方法33fileURLStr =[fileURLStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];34NSURL *fileURL =[NSURL URLWithString:fileURLStr];3536//创建请求37NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:fileURL];3839//创建会话(这里使用了一个全局会话)40NSURLSession *session =[NSURLSession sharedSession];4142//创建下载任务,并且启动他;在非主线程中执行43NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {44__blockvoid(^updateUI)();//声明用于主线程更新 UI 的代码块4546if(!error) {47NSLog(@"下载后的临时保存路径:%@", location);4849NSString *savePath =[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];50savePath =[savePath stringByAppendingPathComponent:_lblFileName.text];51NSURL *saveURL =[NSURL fileURLWithPath:savePath];52NSError *saveError;53NSFileManager *fileManager =[NSFileManager defaultManager];54//判断是否存在旧的目标文件,如果存在就先移除;避免无法复制问题55if([fileManager fileExistsAtPath:savePath]) {56[fileManager removeItemAtPath:savePath error:&saveError];57if(saveError) {58NSLog(@"移除旧的目标文件失败,错误信息:%@", saveError.localizedDescription);5960updateUI = ^{61_lblMessage.text =@"下载失败";62};63}64}65if(!saveError) {66//把源文件复制到目标文件,当目标文件存在时,会抛出一个错误到 error 参数指向的对象实例67//方法一(path 不能有 file://前缀)68//[fileManager copyItemAtPath:[location path]69//toPath:savePath70//error:&saveError];7172//方法二73[fileManager copyItemAtURL:location74toURL:saveURL75error:&saveError];7677if(!saveError) {78NSLog(@"保存成功");7980updateUI = ^{81_lblMessage.text =@"下载完成";82};83}else{84NSLog(@"保存失败,错误信息:%@", saveError.localizedDescription);8586updateUI = ^{87_lblMessage.text =@"下载失败";88};89}90}9192}else{93NSLog(@"下载失败,错误信息:%@", error.localizedDescription);9495updateUI = ^{96_lblMessage.text =@"下载失败";97};98}99100dispatch_async(dispatch_get_main_queue(), updateUI);//使用主队列异步方式(主线程)执行更新 UI 的代码块101}];102[downloadTask resume];//恢复线程,启动任务103}104105@end

NSURLSessionViewController.xib

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

View Code

NSURLSessionDelegateViewController.h

1#import<UIKit/UIKit.h>23@interfaceNSURLSessionDelegateViewController : UIViewController <NSURLSessionDownloadDelegate>4@property (strong, nonatomic) NSURLSessionDownloadTask *downloadTask;56@property (strong, nonatomic) IBOutlet UILabel *lblFileName;7@property (strong, nonatomic) IBOutlet UIProgressView *progVDownloadFile;8@property (strong, nonatomic) IBOutlet UILabel *lblMessage;9@property (strong, nonatomic) IBOutlet UIButton *btnDownloadFile;10@property (strong, nonatomic) IBOutlet UIButton *btnCancel;11@property (strong, nonatomic) IBOutlet UIButton *btnSuspend;12@property (strong, nonatomic) IBOutlet UIButton *btnResume;1314@end

NSURLSessionDelegateViewController.m

1#import"NSURLSessionDelegateViewController.h"2#import"UIButton+BeautifulButton.h"34@interfaceNSURLSessionDelegateViewController ()5- (void)layoutUI;6- (NSURLSession *)defaultSession;7- (NSURLSession *)backgroundSession;8- (void)updateProgress:(int64_t)receiveDataLength totalDataLength:(int64_t)totalDataLength;9@end1011@implementationNSURLSessionDelegateViewController1213- (void)viewDidLoad {14[super viewDidLoad];1516[self layoutUI];17}1819- (void)didReceiveMemoryWarning {20[super didReceiveMemoryWarning];21//Dispose of any resources that can be recreated.22}2324- (void)layoutUI {25self.navigationItem.title =kTitleOfNSURLSessionDelegate;26self.view.backgroundColor = [UIColor colorWithWhite:0.95alpha:1.000];2728[_btnDownloadFile beautifulButton:nil];29[_btnCancel beautifulButton:[UIColor redColor]];30[_btnSuspend beautifulButton:[UIColor purpleColor]];31[_btnResume beautifulButton:[UIColor orangeColor]];32}3334- (NSURLSession *)defaultSession {35/*36NSURLSession 支持进程三种会话:371、defaultSessionConfiguration:进程内会话(默认会话),用硬盘来缓存数据。382、ephemeralSessionConfiguration:临时的进程内会话(内存),不会将 cookie、缓存储存到本地,只会放到内存中,当应用程序退出后数据也会消失。393、backgroundSessionConfiguration:后台会话,相比默认会话,该会话会在后台开启一个线程进行网络数据处理。40*/4142//创建会话配置「进程内会话」43NSURLSessionConfiguration *sessionConfiguration =[NSURLSessionConfiguration defaultSessionConfiguration];44sessionConfiguration.timeoutIntervalForRequest =60.0;//请求超时时间;默认为60秒45sessionConfiguration.allowsCellularAccess = YES;//是否允许蜂窝网络访问(2G/3G/4G)46sessionConfiguration.HTTPMaximumConnectionsPerHost =4;//限制每次最多连接数;在 iOS 中默认值为44748//创建会话49NSURLSession *session =[NSURLSession sessionWithConfiguration:sessionConfiguration50delegate:self51delegateQueue:nil];52returnsession;53}5455- (NSURLSession *)backgroundSession {56staticNSURLSession *session;57staticdispatch_once_t onceToken;58dispatch_once(&onceToken, ^{//应用程序生命周期内,只执行一次;保证只有一个「后台会话」59//创建会话配置「后台会话」60NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"KMDownloadFile.NSURLSessionDelegateViewController"];61sessionConfiguration.timeoutIntervalForRequest =60.0;//请求超时时间;默认为60秒62sessionConfiguration.allowsCellularAccess = YES;//是否允许蜂窝网络访问(2G/3G/4G)63sessionConfiguration.HTTPMaximumConnectionsPerHost =4;//限制每次最多连接数;在 iOS 中默认值为464sessionConfiguration.discretionary = YES;//是否自动选择最佳网络访问,仅对「后台会话」有效6566//创建会话67session =[NSURLSession sessionWithConfiguration:sessionConfiguration68delegate:self69delegateQueue:nil];70});71returnsession;72}7374- (void)updateProgress:(int64_t)receiveDataLength totalDataLength:(int64_t)totalDataLength; {75dispatch_async(dispatch_get_main_queue(), ^{//使用主队列异步方式(主线程)执行更新 UI 操作76if(receiveDataLength ==totalDataLength) {77_lblMessage.text =@"下载完成";78kApplication.networkActivityIndicatorVisible =NO;79}else{80_lblMessage.text =@"下载中...";81kApplication.networkActivityIndicatorVisible =YES;82_progVDownloadFile.progress = (float)receiveDataLength /totalDataLength;83}84});85}8687- (IBAction)downloadFile:(id)sender {88NSString *fileURLStr =kFileURLStr;89//编码操作;对应的解码操作是用 stringByRemovingPercentEncoding 方法90fileURLStr =[fileURLStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];91NSURL *fileURL =[NSURL URLWithString:fileURLStr];9293//创建请求94NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:fileURL];9596//创建会话「进程内会话」;如要用「后台会话」就使用自定义的[self backgroundSession] 方法97NSURLSession *session =[self defaultSession];9899//创建下载任务,并且启动他;在非主线程中执行100_downloadTask =[session downloadTaskWithRequest:request];101[_downloadTask resume];102103/*104会话任务状态105typedef NS_ENUM(NSInteger, NSURLSessionTaskState) {106NSURLSessionTaskStateRunning = 0, //正在执行107NSURLSessionTaskStateSuspended = 1, //已挂起108NSURLSessionTaskStateCanceling = 2, //正在取消109NSURLSessionTaskStateCompleted = 3, //已完成110} NS_ENUM_AVAILABLE(NSURLSESSION_AVAILABLE, 7_0);111*/112}113114- (IBAction)cancel:(id)sender {115[_downloadTask cancel];116}117118- (IBAction)suspend:(id)sender {119[_downloadTask suspend];120kApplication.networkActivityIndicatorVisible =NO;121}122123- (IBAction)resume:(id)sender {124[_downloadTask resume];125}126127#pragmamark - NSURLSessionDownloadDelegate128- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {129NSLog(@"已经接收到响应数据,数据长度为%lld字节...", totalBytesWritten);130131[self updateProgress:totalBytesWritten totalDataLength:totalBytesExpectedToWrite];132}133134- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {135//下载文件会临时保存,正常流程下系统最终会自动清除此临时文件;保存路径目录根据会话类型而有所不同:136//「进程内会话(默认会话)」和「临时的进程内会话(内存)」,路径目录为:/tmp,可以通过 NSTemporaryDirectory() 方法获取137//「后台会话」,路径目录为:/Library/Caches/com.apple.nsurlsessiond/Downloads/com.kenmu.KMDownloadFile138NSLog(@"已经接收完所有响应数据,下载后的临时保存路径:%@", location);139140__blockvoid(^updateUI)();//声明用于主线程更新 UI 的代码块141142NSString *savePath =[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];143savePath =[savePath stringByAppendingPathComponent:_lblFileName.text];144NSURL *saveURL =[NSURL fileURLWithPath:savePath];145NSError *saveError;146NSFileManager *fileManager =[NSFileManager defaultManager];147//判断是否存在旧的目标文件,如果存在就先移除;避免无法复制问题148if([fileManager fileExistsAtPath:savePath]) {149[fileManager removeItemAtPath:savePath error:&saveError];150if(saveError) {151NSLog(@"移除旧的目标文件失败,错误信息:%@", saveError.localizedDescription);152153updateUI = ^{154_lblMessage.text =@"下载失败";155};156}157}158if(!saveError) {159//把源文件复制到目标文件,当目标文件存在时,会抛出一个错误到 error 参数指向的对象实例160//方法一(path 不能有 file://前缀)161//[fileManager copyItemAtPath:[location path]162//toPath:savePath163//error:&saveError];164165//方法二166[fileManager copyItemAtURL:location167toURL:saveURL168error:&saveError];169170if(!saveError) {171NSLog(@"保存成功");172173updateUI = ^{174_lblMessage.text =@"下载完成";175};176}else{177NSLog(@"保存失败,错误信息:%@", saveError.localizedDescription);178179updateUI = ^{180_lblMessage.text =@"下载失败";181};182}183}184185dispatch_async(dispatch_get_main_queue(), updateUI);//使用主队列异步方式(主线程)执行更新 UI 的代码块186}187188- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {189NSLog(@"无论下载成功还是失败,最终都会执行一次");190191if(error) {192NSString *desc =error.localizedDescription;193NSLog(@"下载失败,错误信息:%@", desc);194195dispatch_async(dispatch_get_main_queue(), ^{//使用主队列异步方式(主线程)执行更新 UI 操作196_lblMessage.text = [desc isEqualToString:@"cancelled"] ?@"下载已取消":@"下载失败";197kApplication.networkActivityIndicatorVisible =NO;198_progVDownloadFile.progress =0.0;199});200}201}202203@end

NSURLSessionDelegateViewController.xib

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

View Code

AFNetworkingViewController.h

1#import<UIKit/UIKit.h>2#import"MBProgressHUD.h"34@interfaceAFNetworkingViewController : UIViewController5@property (strong, nonatomic) MBProgressHUD *hud;67@property (strong, nonatomic) IBOutlet UILabel *lblFileName;8@property (strong, nonatomic) IBOutlet UILabel *lblMessage;9@property (strong, nonatomic) IBOutlet UIButton *btnDownloadFileByConnection;10@property (strong, nonatomic) IBOutlet UIButton *btnDownloadFileBySession;1112@end

AFNetworkingViewController.m

1#import"AFNetworkingViewController.h"2#import"AFNetworking.h"3#import"AFNetworkActivityIndicatorManager.h"4#import"UIButton+BeautifulButton.h"56@interfaceAFNetworkingViewController ()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@end1415@implementationAFNetworkingViewController1617- (void)viewDidLoad {18[super viewDidLoad];1920[self layoutUI];21}2223- (void)didReceiveMemoryWarning {24[super didReceiveMemoryWarning];25//Dispose of any resources that can be recreated.26}2728- (void)showAlert:(NSString *)msg {29UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络情况"30message:msg31delegate:self32cancelButtonTitle:nil33otherButtonTitles:@"确定", nil];34[alert show];35}3637- (void)checkNetwork {38NSURL *baseURL = [NSURL URLWithString:@"http://www.baidu.com/"];39AFHTTPRequestOperationManager *manager =[[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL];4041NSOperationQueue *operationQueue =manager.operationQueue;42[manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {43switch(status) {44caseAFNetworkReachabilityStatusReachableViaWiFi:45[self showAlert:@"Wi-Fi 网络下"];46[operationQueue setSuspended:NO];47

break;48caseAFNetworkReachabilityStatusReachableViaWWAN:49[self showAlert:@"2G/3G/4G 蜂窝移动网络下"];50[operationQueue setSuspended:YES];51

break;52caseAFNetworkReachabilityStatusNotReachable:53default:54[self showAlert:@"未连接网络"];55[operationQueue setSuspended:YES];56

break;57}58}];5960[manager.reachabilityManager startMonitoring];61}6263- (void)layoutUI {64self.navigationItem.title =kTitleOfAFNetworking;65self.view.backgroundColor = [UIColor colorWithWhite:0.95alpha:1.000];6667//条件表达式中,「?:」可以表示在条件不成立的情况,才使用后者赋值,否则使用用于条件判断的前者赋值68//以下语句等同于:UIButton *btn = _btnDownloadFileByConnection ? _btnDownloadFileByConnection : [UIButton new];69//在 .NET 中,相当于使用「??」;在javaScript 中,相当于使用「||」来实现这种类似的判断70UIButton *btn = _btnDownloadFileByConnection ?: [UIButtonnew];71[btn beautifulButton:nil];72[_btnDownloadFileBySession beautifulButton:[UIColor orangeColor]];7374//进度效果75_hud =[[MBProgressHUD alloc] initWithView:self.view];76_hud.mode =MBProgressHUDModeDeterminate;77_hud.labelText =@"下载中...";78[_hud hide:YES];79[self.view addSubview:_hud];8081//检查网络情况82[self checkNetwork];8384//启动网络活动指示器;会根据网络交互情况,实时显示或隐藏网络活动指示器;他通过「通知与消息机制」来实现 [UIApplication sharedApplication].networkActivityIndicatorVisible 的控制85[AFNetworkActivityIndicatorManager sharedManager].enabled =YES;86}8788- (NSMutableURLRequest *)downloadRequest {89NSString *fileURLStr =kFileURLStr;90//编码操作;对应的解码操作是用 stringByRemovingPercentEncoding 方法91fileURLStr =[fileURLStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];92NSURL *fileURL =[NSURL URLWithString:fileURLStr];9394//创建请求95NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:fileURL];96returnrequest;97}9899- (NSURL *)saveURL:(NSURLResponse *)response deleteExistFile:(BOOL)deleteExistFile {100NSString *fileName = response ?[response suggestedFilename] : _lblFileName.text;101102//方法一103//NSString *savePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];104//savePath = [savePath stringByAppendingPathComponent:fileName];105//NSURL *saveURL = [NSURL fileURLWithPath:savePath];106107//方法二108NSURL *saveURL =[[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];109saveURL =[saveURL URLByAppendingPathComponent:fileName];110NSString *savePath =[saveURL path];111112if(deleteExistFile) {113NSError *saveError;114NSFileManager *fileManager =[NSFileManager defaultManager];115//判断是否存在旧的目标文件,如果存在就先移除;避免无法复制问题116if([fileManager fileExistsAtPath:savePath]) {117[fileManager removeItemAtPath:savePath error:&saveError];118if(saveError) {119NSLog(@"移除旧的目标文件失败,错误信息:%@", saveError.localizedDescription);120}121}122}123124returnsaveURL;125}126127- (void)updateProgress:(int64_t)receiveDataLength totalDataLength:(int64_t)totalDataLength; {128dispatch_async(dispatch_get_main_queue(), ^{//使用主队列异步方式(主线程)执行更新 UI 操作129_hud.progress = (float)receiveDataLength /totalDataLength;130131if(receiveDataLength ==totalDataLength) {132_lblMessage.text = receiveDataLength <0?@"下载失败":@"下载完成";133//kApplication.networkActivityIndicatorVisible = NO;134[_hud hide:YES];135}else{136_lblMessage.text =@"下载中...";137//kApplication.networkActivityIndicatorVisible = YES;138[_hud show:YES];139}140});141}142143- (IBAction)downloadFileByConnection:(id)sender {144//创建请求145NSMutableURLRequest *request =[self downloadRequest];146147//创建请求操作148AFHTTPRequestOperation *operation =[[AFHTTPRequestOperation alloc] initWithRequest:request];149NSString *savePath =[[self saveURL:nil deleteExistFile:NO] path];150151[operation setDownloadProgressBlock:^(NSUInteger bytesRead,longlongtotalBytesRead,longlongtotalBytesExpectedToRead) {152NSLog(@"已经接收到响应数据,数据长度为%lld字节...", totalBytesRead);153154[self updateProgress:totalBytesRead totalDataLength:totalBytesExpectedToRead];155}];156157[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation,idresponSEObject) {158NSLog(@"已经接收完所有响应数据");159160NSData *data = (NSData *)responseObject;161[data writeToFile:savePath atomically:YES];//responseObject 的对象类型是 NSData162163[self updateProgress:100totalDataLength:100];164} failure:^(AFHTTPRequestOperation *operation, NSError *error) {165NSLog(@"下载失败,错误信息:%@", error.localizedDescription);166167[self updateProgress:-1totalDataLength:-1];168}];169170//启动请求操作171[operation start];172}173174- (IBAction)downloadFileBySession:(id)sender {175//创建请求176NSMutableURLRequest *request =[self downloadRequest];177178//创建会话配置「进程内会话」179NSURLSessionConfiguration *sessionConfiguration =[NSURLSessionConfiguration defaultSessionConfiguration];180sessionConfiguration.timeoutIntervalForRequest =60.0;//请求超时时间;默认为60秒181sessionConfiguration.allowsCellularAccess = YES;//是否允许蜂窝网络访问(2G/3G/4G)182sessionConfiguration.HTTPMaximumConnectionsPerHost =4;//限制每次最多连接数;在 iOS 中默认值为4183184//创建会话管理器185AFURLSessionManager *sessionManager =[[AFURLSessionManager alloc] initWithSessionConfiguration:sessionConfiguration];186187//创建会话下载任务,并且启动他;在非主线程中执行188NSURLSessionDownloadTask *task =[sessionManager189downloadTaskWithRequest:request190progress:nil191destination:^ NSURL*(NSURL *targetPath, NSURLResponse *response) {192//当 sessionManager 调用 setDownloadTaskDidFinishDownloadingBlock: 方法,并且方法代码块返回值不为 nil 时(优先级高),下面的两句代码是不执行的(优先级低)193NSLog(@"下载后的临时保存路径:%@", targetPath);194return[self saveURL:response deleteExistFile:YES];195} completionHandler:^ (NSURLResponse *response, NSURL *filePath, NSError *error) {196if(!error) {197NSLog(@"下载后的保存路径:%@", filePath);//为上面代码块返回的路径198199[self updateProgress:100totalDataLength:100];200}else{201NSLog(@"下载失败,错误信息:%@", error.localizedDescription);202203[self updateProgress:-1totalDataLength:-1];204}205206[_hud hide:YES];207}];208209//类似 NSURLSessionDownloadDelegate 的方法操作210//- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite;211[sessionManager setDownloadTaskDidWriteDataBlock:^ (NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {212NSLog(@"已经接收到响应数据,数据长度为%lld字节...", totalBytesWritten);213214[self updateProgress:totalBytesWritten totalDataLength:totalBytesExpectedToWrite];215}];216217//- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location;218[sessionManager setDownloadTaskDidFinishDownloadingBlock:^ NSURL*(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location) {219NSLog(@"已经接收完所有响应数据,下载后的临时保存路径:%@", location);220return[self saveURL:nil deleteExistFile:YES];221}];222223[task resume];224}225226@end

AFNetworkingViewController.xib

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

View Cod

AppDelegate.h

1#import<UIKit/UIKit.h>23@interfaceAppDelegate : UIResponder <UIApplicationDelegate>45@property (strong, nonatomic) UIWindow *window;6@property (strong, nonatomic) UINavigationController *navigationController;78@end

AppDelegate.m

1#import"AppDelegate.h"2#import"ViewController.h"34@interfaceAppDelegate ()56@end78@implementationAppDelegate91011- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {12_window =[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];13ViewController *viewController =[[ViewController alloc]14initWithSampleNameArray:@[ kTitleOfNSURLConnection,15kTitleOfNSURLConnectionDelegate,16kTitleOfNSURLSession,17kTitleOfNSURLSessionDelegate,18kTitleOfAFNetworking]];19_navigationController =[[UINavigationController alloc] initWithRootViewController:viewController];20_window.rootViewController =_navigationController;21//[_window addSubview:_navigationController.view];//当_window.rootViewController关联时,这一句可有可无22[_window makeKeyAndVisible];23returnYES;24}2526- (void)applicationWillResignActive:(UIApplication *)application {27}2829- (void)applicationDidEnterBackground:(UIApplication *)application {30}3132- (void)applicationWillEnterForeground:(UIApplication *)application {33}3435- (void)applicationDidBecomeActive:(UIApplication *)application {36}3738- (void)applicationWillTerminate:(UIApplication *)application {39}4041@end

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航