概览

大部分应用程序都或多或少会牵扯到网络开发,例如说新浪微博、微信等,这些应用本身可能采用iOS开发,但是所有的数据支撑都是基于后台网络服务器的。如今,网络编程越来越普遍,孤立的应用通常是没有生命力的。今天就会给大家介绍这部分内容:

  1. Web请求和响应
    1. 使用代理方法
    2. 简化请求方法
    3. 图片缓存
    4. 扩展--文件分段下载
    5. 扩展--文件上传
  2. NSURLSession
    1. 数据请求
    2. 文件上传
    3. 文件下载
    4. 会话
  3. UIWebView
    1. 浏览器实现
    2. UIWebView与页面交互
  4. 网络状态

Web请求和响应

使用代理方法

做过Web开发的朋友应该很清楚,Http是无连接的请求。每个请求request服务器都有一个对应的响应response,无论是asp.net、jsp、php都是基于这种机制开发的。

在Web开发中主要的请求方法有如下几种:

  • GET请求:get是获取数据的意思,数据以明文在URL中传递,受限于URL长度,所以传输数据量比较小。
  • POST请求:post是向服务器提交数据的意思,提交的数据以实际内容形式存放到消息头中进行传递,无法在浏览器url中查看到,大小没有限制。
  • HEAD请求:请求头信息,并不返回请求数据体,而只返回请求头信息,常用用于在文件下载中取得文件大小、类型等信息。

在开发中往往数据存储在服务器端,而客户端(iOS应用)往往通过向服务器端发送请求从服务器端获得数据。要模拟这个过程首先当然是建立服务器端应用,应用的形式没有限制,你可以采用任何Web技术进行开发。假设现在有一个文件服务器,用户输入文件名称就可以下载文件。服务器端程序很简单,只要访问http://192.168.1.208/FileDownload.aspx?file=filename,就可以下载指定filename的文件,由于服务器端开发的内容不是今天的重点在此不再赘述。客户端界面设计如下图:

程序的实现需要借助几个对象:

NSURLRequest:建立了一个请求,可以指定缓存策略、超时时间。和NSURLRequest对应的还有一个NSMutableURLRequest,如果请求定义为NSMutableURLRequest则可以指定请求方法(GET或POST)等信息。

NSURLConnection:用于发送请求,可以指定请求和代理。当前调用NSURLConnection的start方法后开始发送异步请求。

程序代码如下:

  1. //
  2. // KCMainViewController.m
  3. // UrlConnection
  4. //
  5. // Created by Kenshin Cui on 14-3-22.
  6. // Copyright (c) 2014年 Kenshin Cui. All rights reserved.
  7. //
  8.  
  9. #import "KCMainViewController.h"
  10.  
  11. @interface KCMainViewController ()<NSURLConnectionDataDelegate>{
  12. NSMutableData *_data;//响应数据
  13. UITextField *_textField;
  14. UIButton *_button;
  15. UIProgressView *_progressView;
  16. UILabel *_label;
  17. long long _totalLength;
  18. }
  19.  
  20. @end
  21.  
  22. @implementation KCMainViewController
  23.  
  24. #pragma mark - UI方法
  25. - (void)viewDidLoad {
  26. [super viewDidLoad];
  27.  
  28. [self layoutUI];
  29.  
  30. }
  31.  
  32. #pragma mark - 私有方法
  33. #pragma mark 界面布局
  34. -(void)layoutUI{
  35. //地址栏
  36. _textField=[[UITextField alloc]initWithFrame:CGRectMake(10, 50, 300, 25)];
  37. _textField.borderStyle=UITextBorderStyleRoundedRect;
  38. _textField.textColor=[UIColor colorWithRed:0 green:146/255.0 blue:1.0 alpha:1.0];
  39. _textField.text=@"简约至上:交互式设计四策略.epub";
  40. [self.view addSubview:_textField];
  41. //进度条
  42. _progressView=[[UIProgressView alloc]initWithFrame:CGRectMake(10, 100, 300, 25)];
  43. [self.view addSubview:_progressView];
  44. //状态显示
  45. _label=[[UILabel alloc]initWithFrame:CGRectMake(10, 130, 300, 25)];
  46. _label.textColor=[UIColor colorWithRed:0 green:146/255.0 blue:1.0 alpha:1.0];
  47. [self.view addSubview:_label];
  48. //下载按钮
  49. _button=[[UIButton alloc]initWithFrame:CGRectMake(10, 500, 300, 25)];
  50. [_button setTitle:@"下载" forState:UIControlStateNormal];
  51. [_button setTitleColor:[UIColor colorWithRed:0 green:146/255.0 blue:1.0 alpha:1.0] forState:UIControlStateNormal];
  52. [_button addTarget:self action:@selector(sendRequest) forControlEvents:UIControlEventTouchUpInside];
  53. [self.view addSubview:_button];
  54.  
  55. }
  56.  
  57. #pragma mark 更新进度
  58. -(void)updateProgress{
  59. // [[NSOperationQueue mainQueue] addOperationWithBlock:^{
  60. if (_data.length==_totalLength) {
  61. _label.text=@"下载完成";
  62. }else{
  63. _label.text=@"正在下载...";
  64. [_progressView setProgress:(float)_data.length/_totalLength];
  65. }
  66. // }];
  67. }
  68.  
  69. #pragma mark 发送数据请求
  70. -(void)sendRequest{
  71. NSString *urlStr=[NSString stringWithFormat:@"http://192.168.1.208/FileDownload.aspx?file=%@",_textField.text];
  72. //注意对于url中的中文是无法解析的,需要进行url编码(指定编码类型为utf-8)
  73. //另外注意url解码使用stringByRemovingPercentEncoding方法
  74. urlStr=[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  75. //创建url链接
  76. NSURL *url=[NSURL URLWithString:urlStr];
  77. /*创建请求
  78. cachePolicy:缓存策略
  79. a.NSURLRequestUseProtocolCachePolicy 协议缓存,根据response中的Cache-Control字段判断缓存是否有效,如果缓存有效则使用缓存数据否则重新从服务器请求
  80. b.NSURLRequestReloadIgnoringLocalCacheData 不使用缓存,直接请求新数据
  81. c.NSURLRequestReloadIgnoringCacheData 等同于 SURLRequestReloadIgnoringLocalCacheData
  82. d.NSURLRequestReturnCacheDataElseLoad 直接使用缓存数据不管是否有效,没有缓存则重新请求
  83. eNSURLRequestReturnCacheDataDontLoad 直接使用缓存数据不管是否有效,没有缓存数据则失败
  84. timeoutInterval:超时时间设置(默认60s)
  85. */
  86.  
  87. NSURLRequest *request=[[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15.0f];
  88. //创建连接
  89. NSURLConnection *connection=[[NSURLConnection alloc]initWithRequest:request delegate:self];
  90. //启动连接
  91. [connection start];
  92.  
  93. }
  94.  
  95. #pragma mark - 连接代理方法
  96. #pragma mark 开始响应
  97. -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
  98. NSLog(@"receive response.");
  99. _data=[[NSMutableData alloc]init];
  100. _progressView.progress=0;
  101.  
  102. //通过响应头中的Content-Length取得整个响应的总长度
  103. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
  104. NSDictionary *httpResponseHeaderFields = [httpResponse allHeaderFields];
  105. _totalLength = [[httpResponseHeaderFields objectForKey:@"Content-Length"] longLongValue];
  106.  
  107. }
  108.  
  109. #pragma mark 接收响应数据(根据响应内容的大小此方法会被重复调用)
  110. -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
  111. NSLog(@"receive data.");
  112. //连续接收数据
  113. [_data appendData:data];
  114. //更新进度
  115. [self updateProgress];
  116. }
  117.  
  118. #pragma mark 数据接收完成
  119. -(void)connectionDidFinishLoading:(NSURLConnection *)connection{
  120. NSLog(@"loading finish.");
  121.  
  122. //数据接收完保存文件(注意苹果官方要求:下载数据只能保存在缓存目录)
  123. NSString *savePath=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
  124. savePath=[savePath stringByAppendingPathComponent:_textField.text];
  125. [_data writeToFile:savePath atomically:YES];
  126.  
  127. NSLog(@"path:%@",savePath);
  128. }
  129.  
  130. #pragma mark 请求失败
  131. -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
  132. //如果连接超时或者连接地址错误可能就会报错
  133. NSLog(@"connection error,error detail is:%@",error.localizedDescription);
  134. }
  135. @end

运行效果:

需要注意:

  1. 根据响应数据大小不同可能会多次执行- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data方法。

  2. URL中不能出现中文(例如上面使用GET传参数时,file参数就可能是中文),需要对URL进行编码,否则会出错。

简化请求方法

当然,对于上面文件下载这种大数据响应的情况使用代理方法处理响应具有一定的优势(可以获得传输进度)。但是如果现响应数据不是文件而是一段字符串(注意web请求的数据可以是字符串或者二进制,上面文件下载示例中响应数据是二进制),那么采用代理方法处理服务器响应就未免有些太麻烦了。其实苹果官方已经提供了下面两种方法处理一般的请求:

+ (void)sendAsynchronousRequest:request: queue:queue:completionHandler:发送一个异步请求

+ (NSData *)sendSynchronousRequest: returningResponse: error:发送一个同步请求

假设在开发一个类似于微博的应用,服务器端返回的是JSON字符串,我们可以使用上面的方法简化整个请求响应的过程。这里会使用在“iOS开发系列--UITableView全面解析”文章中自定义的UITableViewCell来显示微博数据,不清楚的朋友可以看一下前面的内容。

请求过程中需要传递一个用户名和密码,如果全部正确则服务器端返回此用户可以看到的最新微博数据,响应的json格式大致如下:

整个Json最外层是statuses节点,它是一个数组类型,数组中每个元素都是一条微博数据,每条微博数据中除了包含微博信息还包含了发表用户的信息。

首先需要先定义用户模型KCUser

  1. //
  2. // KCUser.h
  3. // UrlConnection
  4. //
  5. // Created by Kenshin Cui on 14-3-22.
  6. // Copyright (c) 2014年 Kenshin Cui. All rights reserved.
  7. //
  8.  
  9. #import <Foundation/Foundation.h>
  10.  
  11. @interface KCUser : NSObject
  12.  
  13. #pragma mark 编号
  14. @property (nonatomic,strong) NSNumber *Id;
  15.  
  16. #pragma mark 用户名
  17. @property (nonatomic,copy) NSString *name;
  18.  
  19. #pragma mark 城市
  20. @property (nonatomic,copy) NSString *city;
  21.  
  22. @end

微博模型KCStatus

KCStatus.h

  1. //
  2. // KCStatus.h
  3. // UITableView
  4. //
  5. // Created by Kenshin Cui on 14-3-1.
  6. // Copyright (c) 2014年 Kenshin Cui. All rights reserved.
  7. //
  8.  
  9. #import <Foundation/Foundation.h>
  10. #import "KCUser.h"
  11.  
  12. @interface KCStatus : NSObject
  13.  
  14. #pragma mark - 属性
  15. @property (nonatomic,strong) NSNumber *Id;//微博id
  16. @property (nonatomic,copy) NSString *profileImageUrl;//头像
  17. @property (nonatomic,strong) KCUser *user;//发送用户
  18. @property (nonatomic,copy) NSString *mbtype;//会员类型
  19. @property (nonatomic,copy) NSString *createdAt;//创建时间
  20. @property (nonatomic,copy) NSString *source;//设备来源
  21. @property (nonatomic,copy) NSString *text;//微博内容
  22.  
  23. @end

KCStatus.m

  1. //
  2. // KCStatus.m
  3. // UITableView
  4. //
  5. // Created by Kenshin Cui on 14-3-1.
  6. // Copyright (c) 2014年 Kenshin Cui. All rights reserved.
  7. //
  8.  
  9. #import "KCStatus.h"
  10.  
  11. @implementation KCStatus
  12.  
  13. -(NSString *)source{
  14. return [NSString stringWithFormat:@"来自 %@",_source];
  15. }
  16. @end

其次需要自定义微博显示的单元格KCStatusTableViewCell,这里需要注意,由于服务器返回数据中头像和会员类型图片已经不在本地,需要从服务器端根据返回JSON的中图片的路径去加载。

KCStatusTableViewCell.h

  1. //
  2. // KCStatusTableViewCell.h
  3. // UITableView
  4. //
  5. // Created by Kenshin Cui on 14-3-1.
  6. // Copyright (c) 2014年 Kenshin Cui. All rights reserved.
  7. //
  8.  
  9. #import <UIKit/UIKit.h>
  10. @class KCStatus;
  11.  
  12. @interface KCStatusTableViewCell : UITableViewCell
  13.  
  14. #pragma mark 微博对象
  15. @property (nonatomic,strong) KCStatus *status;
  16.  
  17. #pragma mark 单元格高度
  18. @property (assign,nonatomic) CGFloat height;
  19.  
  20. @end

KCStatusTableViewCell.m

  1. //
  2. // KCStatusTableViewCell.m
  3. // UITableView
  4. //
  5. // Created by Kenshin Cui on 14-3-1.
  6. // Copyright (c) 2014年 Kenshin Cui. All rights reserved.
  7. //
  8.  
  9. #import "KCStatusTableViewCell.h"
  10. #import "KCStatus.h"
  11. #define KCColor(r,g,b) [UIColor colorWithHue:r/255.0 saturation:g/255.0 brightness:b/255.0 alpha:1] //颜色宏定义
  12. #define kStatusTableViewCellControlSpacing 10 //控件间距
  13. #define kStatusTableViewCellBackgroundColor KCColor(251,251,251)
  14. #define kStatusGrayColor KCColor(50,50,50)
  15. #define kStatusLightGrayColor KCColor(120,120,120)
  16.  
  17. #define kStatusTableViewCellAvatarWidth 40 //头像宽度
  18. #define kStatusTableViewCellAvatarHeight kStatusTableViewCellAvatarWidth
  19. #define kStatusTableViewCellUserNameFontSize 14
  20. #define kStatusTableViewCellMbTypeWidth 13 //会员图标宽度
  21. #define kStatusTableViewCellMbTypeHeight kStatusTableViewCellMbTypeWidth
  22. #define kStatusTableViewCellCreateAtFontSize 12
  23. #define kStatusTableViewCellSourceFontSize 12
  24. #define kStatusTableViewCellTextFontSize 14
  25.  
  26. @interface KCStatusTableViewCell(){
  27. UIImageView *_avatar;//头像
  28. UIImageView *_mbType;//会员类型
  29. UILabel *_userName;
  30. UILabel *_createAt;
  31. UILabel *_source;
  32. UILabel *_text;
  33. }
  34.  
  35. @end
  36.  
  37. @implementation KCStatusTableViewCell
  38.  
  39. - (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
  40. self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
  41. if (self) {
  42. [self initSubView];
  43. }
  44. return self;
  45. }
  46.  
  47. #pragma mark 初始化视图
  48. -(void)initSubView{
  49. //头像控件
  50. _avatar=[[UIImageView alloc]init];
  51. [self addSubview:_avatar];
  52. //用户名
  53. _userName=[[UILabel alloc]init];
  54. _userName.textColor=kStatusGrayColor;
  55. _userName.font=[UIFont systemFontOfSize:kStatusTableViewCellUserNameFontSize];
  56. [self addSubview:_userName];
  57. //会员类型
  58. _mbType=[[UIImageView alloc]init];
  59. [self addSubview:_mbType];
  60. //日期
  61. _createAt=[[UILabel alloc]init];
  62. _createAt.textColor=kStatusLightGrayColor;
  63. _createAt.font=[UIFont systemFontOfSize:kStatusTableViewCellCreateAtFontSize];
  64. [self addSubview:_createAt];
  65. //设备
  66. _source=[[UILabel alloc]init];
  67. _source.textColor=kStatusLightGrayColor;
  68. _source.font=[UIFont systemFontOfSize:kStatusTableViewCellSourceFontSize];
  69. [self addSubview:_source];
  70. //内容
  71. _text=[[UILabel alloc]init];
  72. _text.textColor=kStatusGrayColor;
  73. _text.font=[UIFont systemFontOfSize:kStatusTableViewCellTextFontSize];
  74. _text.numberOfLines=0;
  75. _text.lineBreakMode=NSLineBreakByWordWrapping;
  76. [self addSubview:_text];
  77. }
  78.  
  79. #pragma mark 设置微博
  80. -(void)setStatus:(KCStatus *)status{
  81. //设置头像大小和位置
  82. CGFloat avatarX=10,avatarY=10;
  83. CGRect avatarRect=CGRectMake(avatarX, avatarY, kStatusTableViewCellAvatarWidth, kStatusTableViewCellAvatarHeight);
  84. // _avatar.image=[UIImage imageNamed:status.profileImageUrl];
  85. NSURL *avatarUrl=[NSURL URLWithString:status.profileImageUrl];
  86. NSData *avatarData=[NSData dataWithContentsOfURL:avatarUrl];
  87. UIImage *avatarImage= [UIImage imageWithData:avatarData];
  88. _avatar.image=avatarImage;
  89. _avatar.frame=avatarRect;
  90.  
  91. //设置会员图标大小和位置
  92. CGFloat userNameX= CGRectGetMaxX(_avatar.frame)+kStatusTableViewCellControlSpacing ;
  93. CGFloat userNameY=avatarY;
  94. //根据文本内容取得文本占用空间大小
  95. CGSize userNameSize=[status.user.name sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:kStatusTableViewCellUserNameFontSize]}];
  96. CGRect userNameRect=CGRectMake(userNameX, userNameY, userNameSize.width,userNameSize.height);
  97. _userName.text=status.user.name;
  98. _userName.frame=userNameRect;
  99.  
  100. //设置会员图标大小和位置
  101. CGFloat mbTypeX=CGRectGetMaxX(_userName.frame)+kStatusTableViewCellControlSpacing;
  102. CGFloat mbTypeY=avatarY;
  103. CGRect mbTypeRect=CGRectMake(mbTypeX, mbTypeY, kStatusTableViewCellMbTypeWidth, kStatusTableViewCellMbTypeHeight);
  104. // _mbType.image=[UIImage imageNamed:status.mbtype];
  105. NSURL *mbTypeUrl=[NSURL URLWithString:status.mbtype];
  106. NSData *mbTypeData=[NSData dataWithContentsOfURL:mbTypeUrl];
  107. UIImage *mbTypeImage= [UIImage imageWithData:mbTypeData];
  108. _mbType.image=mbTypeImage;
  109. _mbType.frame=mbTypeRect;
  110.  
  111. //设置发布日期大小和位置
  112. CGSize createAtSize=[status.createdAt sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:kStatusTableViewCellCreateAtFontSize]}];
  113. CGFloat createAtX=userNameX;
  114. CGFloat createAtY=CGRectGetMaxY(_avatar.frame)-createAtSize.height;
  115. CGRect createAtRect=CGRectMake(createAtX, createAtY, createAtSize.width, createAtSize.height);
  116. _createAt.text=status.createdAt;
  117. _createAt.frame=createAtRect;
  118.  
  119. //设置设备信息大小和位置
  120. CGSize sourceSize=[status.source sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:kStatusTableViewCellSourceFontSize]}];
  121. CGFloat sourceX=CGRectGetMaxX(_createAt.frame)+kStatusTableViewCellControlSpacing;
  122. CGFloat sourceY=createAtY;
  123. CGRect sourceRect=CGRectMake(sourceX, sourceY, sourceSize.width,sourceSize.height);
  124. _source.text=status.source;
  125. _source.frame=sourceRect;
  126.  
  127. //设置微博内容大小和位置
  128. CGFloat textX=avatarX;
  129. CGFloat textY=CGRectGetMaxY(_avatar.frame)+kStatusTableViewCellControlSpacing;
  130. CGFloat textWidth=self.frame.size.width-kStatusTableViewCellControlSpacing*2;
  131. CGSize textSize=[status.text boundingRectWithSize:CGSizeMake(textWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:kStatusTableViewCellTextFontSize]} context:nil].size;
  132. CGRect textRect=CGRectMake(textX, textY, textSize.width, textSize.height);
  133. _text.text=status.text;
  134. _text.frame=textRect;
  135.  
  136. _height=CGRectGetMaxY(_text.frame)+kStatusTableViewCellControlSpacing;
  137. }
  138.  
  139. #pragma mark 重写选择事件,取消选中
  140. -(void)setSelected:(BOOL)selected animated:(BOOL)animated{
  141.  
  142. }
  143. @end

最后就是KCMainViewController,在这里需要使用NSURLConnection的静态方法发送请求、获得请求数据,然后对请求数据进行JSON序列化,将JSON字符串序列化成微博对象通过UITableView显示到界面中。

  1. //
  2. // KCMainViewController.m
  3. // UrlConnection
  4. //
  5. // Created by Kenshin Cui on 14-3-22.
  6. // Copyright (c) 2014年 Kenshin Cui. All rights reserved.
  7. //
  8.  
  9. #import "KCMainViewController.h"
  10. #import "KCStatusTableViewCell.h"
  11. #import "KCStatus.h"
  12. #import "KCUser.h"
  13. #define kURL @"http://192.168.1.208/ViewStatus.aspx"
  14.  
  15. @interface KCMainViewController ()<UITableViewDataSource,UITableViewDelegate>{
  16. UITableView *_tableView;
  17. NSMutableArray *_status;
  18. NSMutableArray *_statusCells;//存储cell,用于计算高度
  19. NSString *_userName;
  20. NSString *_password;
  21. }
  22.  
  23. @end
  24.  
  25. @implementation KCMainViewController
  26.  
  27. #pragma mark - UI方法
  28. - (void)viewDidLoad {
  29. [super viewDidLoad];
  30.  
  31. _userName=@"KenshinCui";
  32. _password=@"123";
  33.  
  34. [self layoutUI];
  35.  
  36. [self sendRequest];
  37.  
  38. }
  39.  
  40. #pragma mark - 私有方法
  41. #pragma mark 界面布局
  42. -(void)layoutUI{
  43. _tableView =[[UITableView alloc]initWithFrame:[UIScreen mainScreen].applicationFrame style:UITableViewStylePlain];
  44. _tableView.dataSource=self;
  45. _tableView.delegate=self;
  46. [self.view addSubview:_tableView];
  47. }
  48. #pragma mark 加载数据
  49. -(void)loadData:(NSData *)data{
  50. _status=[[NSMutableArray alloc]init];
  51. _statusCells=[[NSMutableArray alloc]init];
  52. /*json序列化
  53. options:序列化选项,枚举类型,但是可以指定为枚举以外的类型,例如指定为0则可以返回NSDictionary或者NSArray
  54. a.NSJSONReadingMutableContainers:返回NSMutableDictionary或NSMutableArray
  55. b.NSJSONReadingMutableLeaves:返回NSMutableString字符串
  56. c.NSJSONReadingAllowFragments:可以解析JSON字符串的外层既不是字典类型(NSMutableDictionary、NSDictionary)又不是数组类型(NSMutableArray、NSArray)的数据,但是必须是有效的JSON字符串
  57. error:错误信息
  58. */
  59. NSError *error;
  60. //将对象序列化为字典
  61. NSDictionary *dic= [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
  62. NSArray *array= (NSArray *)dic[@"statuses"];
  63. [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  64. KCStatus *status=[[KCStatus alloc]init];
  65. //通过KVC给对象赋值
  66. [status setValuesForKeysWithDictionary:obj];
  67.  
  68. KCUser *user=[[KCUser alloc]init];
  69. [user setValuesForKeysWithDictionary:obj[@"user"]];
  70. status.user=user;
  71.  
  72. [_status addObject:status];
  73.  
  74. //存储tableViewCell
  75. KCStatusTableViewCell *cell=[[KCStatusTableViewCell alloc]init];
  76. [_statusCells addObject:cell];
  77.  
  78. }];
  79. }
  80.  
  81. #pragma mark 发送数据请求
  82. -(void)sendRequest{
  83. NSString *urlStr=[NSString stringWithFormat:@"%@",kURL];
  84. //注意对于url中的中文是无法解析的,需要进行url编码(指定编码类型位utf-8)
  85. //另外注意url解码使用stringByRemovingPercentEncoding方法
  86. urlStr=[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  87. //创建url链接
  88. NSURL *url=[NSURL URLWithString:urlStr];
  89.  
  90. /*创建可变请求*/
  91. NSMutableURLRequest *requestM=[[NSMutableURLRequest alloc]initWithURL:url cachePolicy:0 timeoutInterval:5.0f];
  92. [requestM setHTTPMethod:@"POST"];//设置位post请求
  93. //创建post参数
  94. NSString *bodyDataStr=[NSString stringWithFormat:@"userName=%@&password=%@",_userName,_password];
  95. NSData *bodyData=[bodyDataStr dataUsingEncoding:NSUTF8StringEncoding];
  96. [requestM setHTTPBody:bodyData];
  97.  
  98. //发送一个异步请求
  99. [NSURLConnection sendAsynchronousRequest:requestM queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
  100. if (!connectionError) {
  101. // NSString *jsonStr=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
  102. // NSLog(@"jsonStr:%@",jsonStr);
  103. //加载数据
  104. [self loadData:data];
  105.  
  106. //刷新表格
  107. [_tableView reloadData];
  108. }else{
  109. [[NSOperationQueue mainQueue] addOperationWithBlock:^{
  110.  
  111. }];
  112. }
  113. }];
  114.  
  115. }
  116.  
  117. #pragma mark - 数据源方法
  118. #pragma mark 返回分组数
  119. -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
  120. return 1;
  121. }
  122.  
  123. #pragma mark 返回每组行数
  124. -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
  125.  
  126. return _status.count;
  127. }
  128.  
  129. #pragma mark返回每行的单元格
  130. -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
  131. static NSString *cellIdentifier=@"UITableViewCellIdentifierKey1";
  132. KCStatusTableViewCell *cell;
  133. cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
  134. if(!cell){
  135. cell=[[KCStatusTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
  136. }
  137. //在此设置微博,以便重新布局
  138. KCStatus *status=_status[indexPath.row];
  139. cell.status=status;
  140. return cell;
  141. }
  142.  
  143. #pragma mark - 代理方法
  144. #pragma mark 重新设置单元格高度
  145. -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
  146. KCStatusTableViewCell *cell= _statusCells[indexPath.row];
  147. cell.status=_status[indexPath.row];
  148. return cell.height;
  149. }
  150. @end

运行效果:

可以看到使用NSURLConnection封装的静态方法可以直接获得NSData,不需要使用代理一步步自己组装数据。这里采用了POST方式发送请求,使用POST发送请求需要组装数据体,不过数据长度不像GET方式存在限制。从iOS5开始苹果官方提供了JSON序列化和反序列化相关方法(上面程序中仅仅用到了反序列化方法,序列化使用dataWithJSONObject:options:opt error:方法)方便的对数组和字典进行序列化和反序列化。但是注意反序列化参数设置,程序中设置成了0,直接反序列化为不可变对象以提高性能。

注意:

1.现在多数情况下互联网数据都是以JSON格式进行传输,但是有时候也会面对XML存储。在IOS中可以使用NSXMLParser进行XML解析,由于实际使用并不多,在此不再赘述。

2.使用KVC给对象赋值时(通常是NSDictionary或NSMutalbeDictionary)注意对象的属性最好不要定义为基本类型(如int),否则如果属性值为null则会报错,最后定义为ObjC对象类型(如使用NSNumber代替int等);

图片缓存

开发Web类的应用图片缓存问题不得不提及,因为图片的下载相当耗时。对于前面的微博数据,头像和微博类型图标在数据库中是以链接形式存放的,取得链接后还必须进行对应的图片加载。大家都知道图片往往要比文本内容大得多,在UITableView中上下滚动就会重新加载数据,对于文本由于已经加载到本地自然不存在问题,但是对于图片来说如果每次都必须重新从服务器端加载就不太合适了。

解决图片加载的办法有很多,可以事先存储到内存中,也可以保存到临时文件。在内存中存储虽然简单但是往往不可取,因为程序重新启动之后还面临这重新请求的问题,类似于新浪微博、QQ、微信等应用一般会存储在文件中,这样应用程序即使重启也会从文件中读取。但是使用文件缓存图片可能就要自己做很多事情,例如缓存文件是否过期?缓存数据越来越大如何管理存储空间?

这些问题其实很多第三方框架已经做的很好了,实际开发中往往会采用一些第三方框架来处理图片。例如这里可以选用SDWebImage框架。SDWebImage使用起来相当简单,开发者不必过多关心它的缓存和多线程加载问题,一个方法就可以解决。这里直接修改KCStatusTableViewCell中相关代码即可:

  1. #pragma mark 设置微博
  2. -(void)setStatus:(KCStatus *)status{
  3. //设置头像大小和位置
  4. CGFloat avatarX=10,avatarY=10;
  5. CGRect avatarRect=CGRectMake(avatarX, avatarY, kStatusTableViewCellAvatarWidth, kStatusTableViewCellAvatarHeight);
  6.  
  7. NSURL *avatarUrl=[NSURL URLWithString:status.profileImageUrl];
  8. UIImage *defaultAvatar=[UIImage imageNamed:@"defaultAvatar.jpg"];//默认头像
  9. [_avatar sd_setImageWithURL:avatarUrl placeholderImage:defaultAvatar];
  10.  
  11. _avatar.frame=avatarRect;
  12.  
  13. //设置会员图标大小和位置
  14. CGFloat userNameX= CGRectGetMaxX(_avatar.frame)+kStatusTableViewCellControlSpacing ;
  15. CGFloat userNameY=avatarY;
  16. //根据文本内容取得文本占用空间大小
  17. CGSize userNameSize=[status.user.name sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:kStatusTableViewCellUserNameFontSize]}];
  18. CGRect userNameRect=CGRectMake(userNameX, userNameY, userNameSize.width,userNameSize.height);
  19. _userName.text=status.user.name;
  20. _userName.frame=userNameRect;
  21.  
  22. //设置会员图标大小和位置
  23. CGFloat mbTypeX=CGRectGetMaxX(_userName.frame)+kStatusTableViewCellControlSpacing;
  24. CGFloat mbTypeY=avatarY;
  25. CGRect mbTypeRect=CGRectMake(mbTypeX, mbTypeY, kStatusTableViewCellMbTypeWidth, kStatusTableViewCellMbTypeHeight);
  26.  
  27. NSURL *mbTypeUrl=[NSURL URLWithString:status.mbtype];
  28. [_mbType sd_setImageWithURL:mbTypeUrl ];
  29.  
  30. _mbType.frame=mbTypeRect;
  31.  
  32. //设置发布日期大小和位置
  33. CGSize createAtSize=[status.createdAt sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:kStatusTableViewCellCreateAtFontSize]}];
  34. CGFloat createAtX=userNameX;
  35. CGFloat createAtY=CGRectGetMaxY(_avatar.frame)-createAtSize.height;
  36. CGRect createAtRect=CGRectMake(createAtX, createAtY, createAtSize.width, createAtSize.height);
  37. _createAt.text=status.createdAt;
  38. _createAt.frame=createAtRect;
  39.  
  40. //设置设备信息大小和位置
  41. CGSize sourceSize=[status.source sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:kStatusTableViewCellSourceFontSize]}];
  42. CGFloat sourceX=CGRectGetMaxX(_createAt.frame)+kStatusTableViewCellControlSpacing;
  43. CGFloat sourceY=createAtY;
  44. CGRect sourceRect=CGRectMake(sourceX, sourceY, sourceSize.width,sourceSize.height);
  45. _source.text=status.source;
  46. _source.frame=sourceRect;
  47.  
  48. //设置微博内容大小和位置
  49. CGFloat textX=avatarX;
  50. CGFloat textY=CGRectGetMaxY(_avatar.frame)+kStatusTableViewCellControlSpacing;
  51. CGFloat textWidth=self.frame.size.width-kStatusTableViewCellControlSpacing*2;
  52. CGSize textSize=[status.text boundingRectWithSize:CGSizeMake(textWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:kStatusTableViewCellTextFontSize]} context:nil].size;
  53. CGRect textRect=CGRectMake(textX, textY, textSize.width, textSize.height);
  54. _text.text=status.text;
  55. _text.frame=textRect;
  56.  
  57. _height=CGRectGetMaxY(_text.frame)+kStatusTableViewCellControlSpacing;
  58. }

运行效果:

在上面的方法中直接调用了SDWebImage的分类缓存方法设置图片,这个方法可以分配另外一个线程去加载图片(同时对于头像还指定了默认图片,网速较慢时不至于显示空白),图片加载后存放在沙箱的缓存文件夹,如下图:

滚动UITableView再次加载同一个图片时SDWebImage就会自动判断缓存文件是否有效,如果有效就加载缓存文件,否则重新加载。SDWebImage有很多使用的方法,感兴趣的朋友可以访问“SDWebImage Reference)”。

扩展--文件分段下载

通过前面的演示大家应该对于iOS的Web请求有了大致的了解,可以通过代理方法接收数据也可以直接通过静态方法接收数据,但是实际开发中更推荐使用静态方法。关于前面的文件下载示例,更多的是希望大家了解代理方法接收响应数据的过程,实际开发中也不可能使用这种方法进行文件下载。这种下载有个致命的问题:不适合进行大文件分段下载。因为代理方法在接收数据时虽然表面看起来是每次读取一部分响应数据,事实上它只有一次请求并且也只接收了一次服务器响应,只是当响应数据较大时系统会重复调用数据接收方法,每次将已读取的数据拿出一部分交给数据接收方法。这样一来对于上G的文件进行下载,如果中途暂停的话再次请求还是从头开始下载,不适合大文件断点续传(另外说明一点,上面NSURLConnection示例中使用了NSMutableData进行数据接收和追加只是为了方便演示,实际开发建议直接写入文件)。

实际开发文件下载的时候不管是通过代理方法还是静态方法执行请求和响应,我们都会分批请求数据,而不是一次性请求数据。假设一个文件有1G,那么只要每次请求1M的数据,请求1024次也就下载完了。那么如何让服务器每次只返回1M的数据呢?

在网络开发中可以在请求的头文件中设置一个range信息,它代表请求数据的大小。通过这个字段配合服务器端可以精确的控制每次服务器响应的数据范围。例如指定bytes=0-1023,然后在服务器端解析Range信息,返回该文件的0到1023之间的数据的数据即可(共1024Byte)。这样,只要在每次发送请求控制这个头文件信息就可以做到分批请求。

当然,为了让整个数据保持完整,每次请求的数据都需要逐步追加直到整个文件请求完成。但是如何知道整个文件的大小?其实在前面的文件下载演示中大家可以看到,可以通过头文件信息获取整个文件大小。但是这么做的话就必须请求整个数据,这样分段下载就没有任何意义了。所幸在WEB开发中我们还有另一种请求方法“HEAD”,通过这种请求服务器只会响应头信息,其他数据不会返回给客户端,这样一来整个数据的大小也就可以得到了。下面给出完整的程序代码,关键的地方已经给出注释(为了简化代码,这里没有使用代理方法):

KCMainViewController.m

  1. //
  2. // KCMainViewController.m
  3. // UrlConnection
  4. //
  5. // Created by Kenshin Cui on 14-3-22.
  6. // Copyright (c) 2014年 Kenshin Cui. All rights reserved.
  7. //
  8.  
  9. #import "KCMainViewController.h"
  10. #define kUrl @"http://192.168.1.208/FileDownload.aspx"
  11. #define kFILE_BLOCK_SIZE (1024) //每次1KB
  12.  
  13. @interface KCMainViewController ()<NSURLConnectionDataDelegate>{
  14. UITextField *_textField;
  15. UIButton *_button;
  16. UIProgressView *_progressView;
  17. UILabel *_label;
  18. long long _totalLength;
  19. long long _loadedLength;
  20. }
  21.  
  22. @end
  23.  
  24. @implementation KCMainViewController
  25.  
  26. #pragma mark - UI方法
  27. - (void)viewDidLoad {
  28. [super viewDidLoad];
  29.  
  30. [self layoutUI];
  31. }
  32.  
  33. #pragma mark - 私有方法
  34. #pragma mark 界面布局
  35. -(void)layoutUI{
  36. //地址栏
  37. _textField=[[UITextField alloc]initWithFrame:CGRectMake(10, 50, 300, 25)];
  38. _textField.borderStyle=UITextBorderStyleRoundedRect;
  39. _textField.textColor=[UIColor colorWithRed:0 green:146/255.0 blue:1.0 alpha:1.0];
  40. _textField.text=@"1.jpg";
  41. // _textField.text=@"1.jpg";
  42. [self.view addSubview:_textField];
  43. //进度条
  44. _progressView=[[UIProgressView alloc]initWithFrame:CGRectMake(10, 100, 300, 25)];
  45. [self.view addSubview:_progressView];
  46. //状态显示
  47. _label=[[UILabel alloc]initWithFrame:CGRectMake(10, 130, 300, 25)];
  48. _label.textColor=[UIColor colorWithRed:0 green:146/255.0 blue:1.0 alpha:1.0];
  49. [self.view addSubview:_label];
  50. //下载按钮
  51. _button=[[UIButton alloc]initWithFrame:CGRectMake(10, 500, 300, 25)];
  52. [_button setTitle:@"下载" forState:UIControlStateNormal];
  53. [_button setTitleColor:[UIColor colorWithRed:0 green:146/255.0 blue:1.0 alpha:1.0] forState:UIControlStateNormal];
  54. [_button addTarget:self action:@selector(downloadFileAsync) forControlEvents:UIControlEventTouchUpInside];
  55. [self.view addSubview:_button];
  56.  
  57. }
  58.  
  59. #pragma mark 更新进度
  60. -(void)updateProgress{
  61. [[NSOperationQueue mainQueue] addOperationWithBlock:^{
  62. if (_loadedLength==_totalLength) {
  63. _label.text=@"下载完成";
  64. }else{
  65. _label.text=@"正在下载...";
  66. }
  67. [_progressView setProgress:(double)_loadedLength/_totalLength];
  68. }];
  69. }
  70. #pragma mark 取得请求链接
  71. -(NSURL *)getDownloadUrl:(NSString *)fileName{
  72. NSString *urlStr=[NSString stringWithFormat:@"%@?file=%@",kUrl,fileName];
  73. urlStr=[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  74. NSURL *url=[NSURL URLWithString:urlStr];
  75. return url;
  76. }
  77. #pragma mark 取得保存地址(保存在沙盒缓存目录)
  78. -(NSString *)getSavePath:(NSString *)fileName{
  79. NSString *path=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
  80. return [path stringByAppendingPathComponent:fileName];
  81. }
  82. #pragma mark 文件追加
  83. -(void)fileAppend:(NSString *)filePath data:(NSData *)data{
  84. //以可写方式打开文件
  85. NSFileHandle *fileHandle=[NSFileHandle fileHandleForWritingAtPath:filePath];
  86. //如果存在文件则追加,否则创建
  87. if (fileHandle) {
  88. [fileHandle seekToEndOfFile];
  89. [fileHandle writeData:data];
  90. [fileHandle closeFile];//关闭文件
  91. }else{
  92. [data writeToFile:filePath atomically:YES];//创建文件
  93. }
  94. }
  95.  
  96. #pragma mark 取得文件大小
  97. -(long long)getFileTotlaLength:(NSString *)fileName{
  98. NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[self getDownloadUrl:fileName] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:5.0f];
  99. //设置为头信息请求
  100. [request setHTTPMethod:@"HEAD"];
  101.  
  102. NSURLResponse *response;
  103. NSError *error;
  104. //注意这里使用了同步请求,直接将文件大小返回
  105. [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
  106. if (error) {
  107. NSLog(@"detail error:%@",error.localizedDescription);
  108. }
  109. //取得内容长度
  110. return response.expectedContentLength;
  111. }
  112.  
  113. #pragma mark 下载指定块大小的数据
  114. -(void)downloadFile:(NSString *)fileName startByte:(long long)start endByte:(long long)end{
  115. NSString *range=[NSString stringWithFormat:@"Bytes=%lld-%lld",start,end];
  116. NSLog(@"%@",range);
  117. // NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[self getDownloadUrl:fileName]];
  118. NSMutableURLRequest *request= [NSMutableURLRequest requestWithURL:[self getDownloadUrl:fileName] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:5.0f];
  119. //通过请求头设置数据请求范围
  120. [request setValue:range forHTTPHeaderField:@"Range"];
  121.  
  122. NSURLResponse *response;
  123. NSError *error;
  124. //注意这里使用同步请求,避免文件块追加顺序错误
  125. NSData *data= [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
  126. if(!error){
  127. NSLog(@"dataLength=%lld",(long long)data.length);
  128. [self fileAppend:[self getSavePath:fileName] data:data];
  129. }
  130. else{
  131. NSLog(@"detail error:%@",error.localizedDescription);
  132. }
  133. }
  134.  
  135. #pragma mark 文件下载
  136. -(void)downloadFile{
  137. _totalLength=[self getFileTotlaLength:_textField.text];
  138. _loadedLength=0;
  139. long long startSize=0;
  140. long long endSize=0;
  141. //分段下载
  142. while(startSize< _totalLength){
  143. endSize=startSize+kFILE_BLOCK_SIZE-1;
  144. if (endSize>_totalLength) {
  145. endSize=_totalLength-1;
  146. }
  147. [self downloadFile:_textField.text startByte:startSize endByte:endSize];
  148.  
  149. //更新进度
  150. _loadedLength+=(endSize-startSize)+1;
  151. [self updateProgress];
  152.  
  153. startSize+=kFILE_BLOCK_SIZE;
  154.  
  155. }
  156. }
  157.  
  158. #pragma mark 异步下载文件
  159. -(void)downloadFileAsync{
  160. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  161. [self downloadFile];
  162. });
  163. }
  164.  
  165. @end

运行效果:

下载文件的生成过程:

分段下载的过程实现并不复杂,主要是需要配合后台进行响应进行操作。针对不同的开发技术,服务器端处理方式稍有差别,但是基本原理是一样的,那就是读取Range信息,按需提供相应数据。

扩展--文件上传

在做WEB应用程序开发时,如果要上传一个文件往往会给form设置一个enctype=”multipart/form-data”的属性,不设置这个值在后台无法正常接收文件。在WEB开发过程中,form的这个属性其实本质就是指定请求头中Content-Type类型,当然使用GET方法提交就不用说了,必须使用URL编码。但是如果使用POST方法传递数据其实也是类似的,同样需要进行编码,具体编码方式其实就是通过enctype属性进行设置的。常用的属性值有:

  • application/x-www-form-urlencoded:默认值,发送前对所有发送数据进行url编码,支持浏览器访问,通常文本内容提交常用这种方式。

  • multipart/form-data:多部分表单数据,支持浏览器访问,不进行任何编码,通常用于文件传输(此时传递的是二进制数据) 。
  • text/plain:普通文本数据类型,支持浏览器访问,发送前其中的空格替换为“+”,但是不对特殊字符编码。
  • application/json:json数据类型,浏览器访问不支持 。
  • text/xml:xml数据类型,浏览器访问不支持。

要实现文件上传,必须采用POST上传,同时请求类型必须是multipart/form-data。在Web开发中,开发人员不必过多的考虑mutiparty/form-data更多的细节,一般使用file控件即可完成文件上传。但是在iOS中如果要实现文件上传,就没有那么简单了,我们必须了解这种数据类型的请求是如何工作的。

下面是在浏览器中上传一个文件时,发送的请求头:

这是发送的请求体内容:

在请求头中,最重要的就是Content-Type,它的值分为两部分:前半部分是内容类型,前面已经解释过了;后面是边界boundary用来分隔表单中不同部分的数据,后面一串数字是浏览器自动生成的,它的格式并不固定,可以是任意字符。和请求体中的源代码部分进行对比不难发现其实boundary的内容和请求体的数据部分前的字符串相比少了两个“--”。请求体中Content-Disposition中指定了表单元素的name属性和文件名称,同时指定了Content-Type表示文件类型。当然,在请求体中最重要的就是后面的数据部分,它其实就是二进制字符串。由此可以得出以下结论,请求体内容由如下几部分按顺序执行组成:

  1. --boundary
  2. Content-Disposition:form-data;name=”表单控件名称”;filename=”上传文件名称”
  3. Content-Type:文件MIME Types
  4.  
  5. 文件二进制数据;
  6.  
  7. --boundary--

了解这些信息后,只要使用POST方法给服务器端发送请求并且请求内容按照上面的格式设置即可。

下面是实现代码:

  1. //
  2. // KCMainViewController.m
  3. // UrlConnection
  4. //
  5. // Created by Kenshin Cui on 14-3-22.
  6. // Copyright (c) 2014年 Kenshin Cui. All rights reserved.
  7. //
  8.  
  9. #import "KCMainViewController.h"
  10. #define kUrl @"http://192.168.1.208/FileUpload.aspx"
  11. #define kBOUNDARY_STRING @"KenshinCui"
  12.  
  13. @interface KCMainViewController ()<NSURLConnectionDataDelegate>{
  14. UITextField *_textField;
  15. UIButton *_button;
  16. }
  17.  
  18. @end
  19.  
  20. @implementation KCMainViewController
  21.  
  22. #pragma mark - UI方法
  23. - (void)viewDidLoad {
  24. [super viewDidLoad];
  25.  
  26. [self layoutUI];
  27.  
  28. }
  29.  
  30. #pragma mark - 私有方法
  31. #pragma mark 界面布局
  32. -(void)layoutUI{
  33. //地址栏
  34. _textField=[[UITextField alloc]initWithFrame:CGRectMake(10, 50, 300, 25)];
  35. _textField.borderStyle=UITextBorderStyleRoundedRect;
  36. _textField.textColor=[UIColor colorWithRed:0 green:146/255.0 blue:1.0 alpha:1.0];
  37. _textField.text=@"pic.jpg";
  38. [self.view addSubview:_textField];
  39. //上传按钮
  40. _button=[[UIButton alloc]initWithFrame:CGRectMake(10, 500, 300, 25)];
  41. [_button setTitle:@"上传" forState:UIControlStateNormal];
  42. [_button setTitleColor:[UIColor colorWithRed:0 green:146/255.0 blue:1.0 alpha:1.0] forState:UIControlStateNormal];
  43. [_button addTarget:self action:@selector(uploadFile) forControlEvents:UIControlEventTouchUpInside];
  44. [self.view addSubview:_button];
  45.  
  46. }
  47.  
  48. #pragma mark 取得请求链接
  49. -(NSURL *)getUploadUrl:(NSString *)fileName{
  50. NSString *urlStr=[NSString stringWithFormat:@"%@?file=%@",kUrl,fileName];
  51. urlStr=[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  52. NSURL *url=[NSURL URLWithString:urlStr];
  53. return url;
  54. }
  55. #pragma mark 取得mime types
  56. -(NSString *)getMIMETypes:(NSString *)fileName{
  57. return @"image/jpg";
  58. }
  59. #pragma mark 取得数据体
  60. -(NSData *)getHttpBody:(NSString *)fileName{
  61. NSMutableData *dataM=[NSMutableData data];
  62. NSString *strTop=[NSString stringWithFormat:@"--%@\nContent-Disposition: form-data; name=\"file1\"; filename=\"%@\"\nContent-Type: %@\n\n",kBOUNDARY_STRING,fileName,[self getMIMETypes:fileName]];
  63. NSString *strBottom=[NSString stringWithFormat:@"\n--%@--",kBOUNDARY_STRING];
  64. NSString *filePath=[[NSBundle mainBundle] pathForResource:fileName ofType:nil];
  65. NSData *fileData=[NSData dataWithContentsOfFile:filePath];
  66. [dataM appendData:[strTop dataUsingEncoding:NSUTF8StringEncoding]];
  67. [dataM appendData:fileData];
  68. [dataM appendData:[strBottom dataUsingEncoding:NSUTF8StringEncoding]];
  69. return dataM;
  70. }
  71.  
  72. #pragma mark 上传文件
  73. -(void)uploadFile{
  74. NSString *fileName=_textField.text;
  75.  
  76. NSMutableURLRequest *request= [NSMutableURLRequest requestWithURL:[self getUploadUrl:fileName] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:5.0f];
  77.  
  78. request.HTTPMethod=@"POST";
  79.  
  80. NSData *data=[self getHttpBody:fileName];
  81.  
  82. //通过请求头设置
  83. [request setValue:[NSString stringWithFormat:@"%lu",(unsigned long)data.length] forHTTPHeaderField:@"Content-Length"];
  84. [request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",kBOUNDARY_STRING] forHTTPHeaderField:@"Content-Type"];
  85.  
  86. //设置数据体
  87. request.HTTPBody=data;
  88.  
  89. //发送请求
  90. [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
  91. if(connectionError){
  92. NSLog(@"error:%@",connectionError.localizedDescription);
  93. }
  94. }];
  95. }
  96. @end

NSURLSession

NSURLConnection是2003年伴随着Safari一起发行的网络开发API,距今已经有十一年。当然,在这十一年间它表现的相当优秀,有大量的应用基础,这也是为什么前面花了那么长时间对它进行详细介绍的原因。但是这些年伴随着iPhone、iPad的发展,对于NSURLConnection设计理念也提出了新的挑战。在2013年WWDC上苹果揭开了NSURLSession的面纱,将它作为NSURLConnection的继任者。相比较NSURLConnection,NSURLSession提供了配置会话缓存、协议、cookie和证书能力,这使得网络架构和应用程序可以独立工作、互不干扰。另外,NSURLSession另一个重要的部分是会话任务,它负责加载数据,在客户端和服务器端进行文件的上传下载。

通过前面的介绍大家可以看到,NSURLConnection完成的三个主要任务:获取数据(通常是JSON、XML等)、文件上传、文件下载。其实在NSURLSession时代,他们分别由三个任务来完成:NSURLSessionData、NSURLSessionUploadTask、NSURLSessionDownloadTask,这三个类都是NSURLSessionTask这个抽象类的子类,相比直接使用NSURLConnection,NSURLSessionTask支持任务的暂停、取消和恢复,并且默认任务运行在其他非主线程中,具体关系图如下:

数据请求

前面通过请求一个微博数据进行数据请求演示,现在通过NSURLSessionDataTask实现这个功能,其实现流程与使用NSURLConnection的静态方法类似,下面是主要代码:

  1. -(void)loadJsonData{
  2. //1.创建url
  3. NSString *urlStr=[NSString stringWithFormat:@"http://192.168.1.208/ViewStatus.aspx?userName=%@&password=%@",@"KenshinCui",@"123"];
  4. urlStr =[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  5. NSURL *url=[NSURL URLWithString:urlStr];
  6. //2.创建请求
  7. NSURLRequest *request=[NSURLRequest requestWithURL:url];
  8.  
  9. //3.创建会话(这里使用了一个全局会话)并且启动任务
  10. NSURLSession *session=[NSURLSession sharedSession];
  11. //从会话创建任务
  12. NSURLSessionDataTask *dataTask=[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
  13. if (!error) {
  14. NSString *dataStr=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
  15. NSLog(@"%@",dataStr);
  16. }else{
  17. NSLog(@"error is :%@",error.localizedDescription);
  18. }
  19. }];
  20.  
  21. [dataTask resume];//恢复线程,启动任务
  22. }

文件上传

下面看一下如何使用NSURLSessionUploadTask实现文件上传,这里贴出主要的几个方法:

  1. #pragma mark 取得mime types
  2. -(NSString *)getMIMETypes:(NSString *)fileName{
  3. return @"image/jpg";
  4. }
  5. #pragma mark 取得数据体
  6. -(NSData *)getHttpBody:(NSString *)fileName{
  7. NSString *boundary=@"KenshinCui";
  8. NSMutableData *dataM=[NSMutableData data];
  9. NSString *strTop=[NSString stringWithFormat:@"--%@\nContent-Disposition: form-data; name=\"file1\"; filename=\"%@\"\nContent-Type: %@\n\n",boundary,fileName,[self getMIMETypes:fileName]];
  10. NSString *strBottom=[NSString stringWithFormat:@"\n--%@--",boundary];
  11. NSString *filePath=[[NSBundle mainBundle] pathForResource:fileName ofType:nil];
  12. NSData *fileData=[NSData dataWithContentsOfFile:filePath];
  13. [dataM appendData:[strTop dataUsingEncoding:NSUTF8StringEncoding]];
  14. [dataM appendData:fileData];
  15. [dataM appendData:[strBottom dataUsingEncoding:NSUTF8StringEncoding]];
  16. return dataM;
  17. }
  18. #pragma mark 上传文件
  19. -(void)uploadFile{
  20. NSString *fileName=@"pic.jpg";
  21. //1.创建url
  22. NSString *urlStr=@"http://192.168.1.208/FileUpload.aspx";
  23. urlStr =[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  24. NSURL *url=[NSURL URLWithString:urlStr];
  25. //2.创建请求
  26. NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
  27. request.HTTPMethod=@"POST";
  28.  
  29. //3.构建数据
  30. NSString *path=[[NSBundle mainBundle] pathForResource:fileName ofType:nil];
  31. NSData *data=[self getHttpBody:fileName];
  32. request.HTTPBody=data;
  33.  
  34. [request setValue:[NSString stringWithFormat:@"%lu",(unsigned long)data.length] forHTTPHeaderField:@"Content-Length"];
  35. [request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",@"KenshinCui"] forHTTPHeaderField:@"Content-Type"];
  36.  
  37. //4.创建会话
  38. NSURLSession *session=[NSURLSession sharedSession];
  39. NSURLSessionUploadTask *uploadTask=[session uploadTaskWithRequest:request fromData:data completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
  40. if (!error) {
  41. NSString *dataStr=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
  42. NSLog(@"%@",dataStr);
  43. }else{
  44. NSLog(@"error is :%@",error.localizedDescription);
  45. }
  46. }];
  47.  
  48. [uploadTask resume];
  49. }

如果仅仅通过上面的方法或许文件上传还看不出和NSURLConnection之间的区别,因为拼接上传数据的过程和前面是一样的。事实上在NSURLSessionUploadTask中还提供了一个- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request fromFile:(NSURL *)fileURL completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler方法用于文件上传。这个方法通常会配合“PUT”请求进行使用,由于PUT方法包含在Web DAV协议中,不同的WEB服务器其配置启用PUT的方法也不同,并且出于安全考虑,各类WEB服务器默认对PUT请求也是拒绝的,所以实际使用时还需做重分考虑,在这里不具体介绍,有兴趣的朋友可以自己试验一下。

文件下载

使用NSURLSessionDownloadTask下载文件的过程与前面差不多,需要注意的是文件下载文件之后会自动保存到一个临时目录,需要开发人员自己将此文件重新放到其他指定的目录中。

  1. -(void)downloadFile{
  2. //1.创建url
  3. NSString *fileName=@"1.jpg";
  4. NSString *urlStr=[NSString stringWithFormat: @"http://192.168.1.208/FileDownload.aspx?file=%@",fileName];
  5. urlStr =[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  6. NSURL *url=[NSURL URLWithString:urlStr];
  7. //2.创建请求
  8. NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
  9.  
  10. //3.创建会话(这里使用了一个全局会话)并且启动任务
  11. NSURLSession *session=[NSURLSession sharedSession];
  12.  
  13. NSURLSessionDownloadTask *downloadTask=[session downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
  14. if (!error) {
  15. //注意location是下载后的临时保存路径,需要将它移动到需要保存的位置
  16.  
  17. NSError *saveError;
  18. NSString *cachePath=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
  19. NSString *savePath=[cachePath stringByAppendingPathComponent:fileName];
  20. NSLog(@"%@",savePath);
  21. NSURL *saveUrl=[NSURL fileURLWithPath:savePath];
  22. [[NSFileManager defaultManager] copyItemAtURL:location toURL:saveUrl error:&saveError];
  23. if (!saveError) {
  24. NSLog(@"save sucess.");
  25. }else{
  26. NSLog(@"error is :%@",saveError.localizedDescription);
  27. }
  28.  
  29. }else{
  30. NSLog(@"error is :%@",error.localizedDescription);
  31. }
  32. }];
  33.  
  34. [downloadTask resume];
  35. }

会话

NSURLConnection通过全局状态来管理cookies、认证信息等公共资源,这样如果遇到两个连接需要使用不同的资源配置情况时就无法解决了,但是这个问题在NSURLSession中得到了解决。NSURLSession同时对应着多个连接,会话通过工厂方法来创建,同一个会话中使用相同的状态信息。NSURLSession支持进程三种会话:

  1. defaultSessionConfiguration:进程内会话(默认会话),用硬盘来缓存数据。

  2. ephemeralSessionConfiguration:临时的进程内会话(内存),不会将cookie、缓存储存到本地,只会放到内存中,当应用程序退出后数据也会消失。
  3. backgroundSessionConfiguration:后台会话,相比默认会话,该会话会在后台开启一个线程进行网络数据处理。

下面将通过一个文件下载功能对两种会话进行演示,在这个过程中也会用到任务的代理方法对上传操作进行更加细致的控制。下面先看一下使用默认会话下载文件,代码中演示了如何通过NSURLSessionConfiguration进行会话配置,如果通过代理方法进行文件下载进度展示(类似于前面中使用NSURLConnection代理方法,其实下载并未分段,如果需要分段需要配合后台进行),同时在这个过程中可以准确控制任务的取消、挂起和恢复。

  1. //
  2. // KCMainViewController.m
  3. // URLSession
  4. //
  5. // Created by Kenshin Cui on 14-03-23.
  6. // Copyright (c) 2014年 Kenshin Cui. All rights reserved.
  7. //
  8.  
  9. #import "KCMainViewController.h"
  10.  
  11. @interface KCMainViewController ()<NSURLSessionDownloadDelegate>{
  12. UITextField *_textField;
  13. UIProgressView *_progressView;
  14. UILabel *_label;
  15. UIButton *_btnDownload;
  16. UIButton *_btnCancel;
  17. UIButton *_btnSuspend;
  18. UIButton *_btnResume;
  19. NSURLSessionDownloadTask *_downloadTask;
  20. }
  21.  
  22. @end
  23.  
  24. @implementation KCMainViewController
  25.  
  26. #pragma mark - UI方法
  27. - (void)viewDidLoad {
  28. [super viewDidLoad];
  29.  
  30. [self layoutUI];
  31. }
  32.  
  33. #pragma mark 界面布局
  34. -(void)layoutUI{
  35. //地址栏
  36. _textField=[[UITextField alloc]initWithFrame:CGRectMake(10, 50, 300, 25)];
  37. _textField.borderStyle=UITextBorderStyleRoundedRect;
  38. _textField.textColor=[UIColor colorWithRed:0 green:146/255.0 blue:1.0 alpha:1.0];
  39. _textField.text=@"[Objective-C.程序设计(第4版)].(斯蒂芬).林冀等.扫描版[电子书www.minxue.net].pdf";
  40. [self.view addSubview:_textField];
  41. //进度条
  42. _progressView=[[UIProgressView alloc]initWithFrame:CGRectMake(10, 100, 300, 25)];
  43. [self.view addSubview:_progressView];
  44. //状态显示
  45. _label=[[UILabel alloc]initWithFrame:CGRectMake(10, 130, 300, 25)];
  46. _label.textColor=[UIColor colorWithRed:0 green:146/255.0 blue:1.0 alpha:1.0];
  47. [self.view addSubview:_label];
  48. //下载按钮
  49. _btnDownload=[[UIButton alloc]initWithFrame:CGRectMake(20, 500, 50, 25)];
  50. [_btnDownload setTitle:@"下载" forState:UIControlStateNormal];
  51. [_btnDownload setTitleColor:[UIColor colorWithRed:0 green:146/255.0 blue:1.0 alpha:1.0] forState:UIControlStateNormal];
  52. [_btnDownload addTarget:self action:@selector(downloadFile) forControlEvents:UIControlEventTouchUpInside];
  53. [self.view addSubview:_btnDownload];
  54. //取消按钮
  55. _btnCancel=[[UIButton alloc]initWithFrame:CGRectMake(100, 500, 50, 25)];
  56. [_btnCancel setTitle:@"取消" forState:UIControlStateNormal];
  57. [_btnCancel setTitleColor:[UIColor colorWithRed:0 green:146/255.0 blue:1.0 alpha:1.0] forState:UIControlStateNormal];
  58. [_btnCancel addTarget:self action:@selector(cancelDownload) forControlEvents:UIControlEventTouchUpInside];
  59. [self.view addSubview:_btnCancel];
  60. //挂起按钮
  61. _btnSuspend=[[UIButton alloc]initWithFrame:CGRectMake(180, 500, 50, 25)];
  62. [_btnSuspend setTitle:@"挂起" forState:UIControlStateNormal];
  63. [_btnSuspend setTitleColor:[UIColor colorWithRed:0 green:146/255.0 blue:1.0 alpha:1.0] forState:UIControlStateNormal];
  64. [_btnSuspend addTarget:self action:@selector(suspendDownload) forControlEvents:UIControlEventTouchUpInside];
  65. [self.view addSubview:_btnSuspend];
  66. //恢复按钮
  67. _btnResume=[[UIButton alloc]initWithFrame:CGRectMake(260, 500, 50, 25)];
  68. [_btnResume setTitle:@"恢复" forState:UIControlStateNormal];
  69. [_btnResume setTitleColor:[UIColor colorWithRed:0 green:146/255.0 blue:1.0 alpha:1.0] forState:UIControlStateNormal];
  70. [_btnResume addTarget:self action:@selector(resumeDownload) forControlEvents:UIControlEventTouchUpInside];
  71. [self.view addSubview:_btnResume];
  72. }
  73. #pragma mark 设置界面状态
  74. -(void)setUIStatus:(int64_t)totalBytesWritten expectedToWrite:(int64_t)totalBytesExpectedToWrite{
  75. dispatch_async(dispatch_get_main_queue(), ^{
  76. _progressView.progress=(float)totalBytesWritten/totalBytesExpectedToWrite;
  77. if (totalBytesWritten==totalBytesExpectedToWrite) {
  78. _label.text=@"下载完成";
  79. [UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
  80. _btnDownload.enabled=YES;
  81. }else{
  82. _label.text=@"正在下载...";
  83. [UIApplication sharedApplication].networkActivityIndicatorVisible=YES;
  84. }
  85. });
  86. }
  87.  
  88. #pragma mark 文件下载
  89. -(void)downloadFile{
  90. //1.创建url
  91. NSString *fileName=_textField.text;
  92. NSString *urlStr=[NSString stringWithFormat: @"http://192.168.1.208/FileDownload.aspx?file=%@",fileName];
  93. urlStr =[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  94. NSURL *url=[NSURL URLWithString:urlStr];
  95. //2.创建请求
  96. NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
  97.  
  98. //3.创建会话
  99. //默认会话
  100. NSURLSessionConfiguration *sessionConfig=[NSURLSessionConfiguration defaultSessionConfiguration];
  101. sessionConfig.timeoutIntervalForRequest=5.0f;//请求超时时间
  102. sessionConfig.allowsCellularAccess=true;//是否允许蜂窝网络下载(2G/3G/4G)
  103. //创建会话
  104. NSURLSession *session=[NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];//指定配置和代理
  105. _downloadTask=[session downloadTaskWithRequest:request];
  106.  
  107. [_downloadTask resume];
  108. }
  109. #pragma mark 取消下载
  110. -(void)cancelDownload{
  111. [_downloadTask cancel];
  112.  
  113. }
  114. #pragma mark 挂起下载
  115. -(void)suspendDownload{
  116. [_downloadTask suspend];
  117. }
  118. #pragma mark 恢复下载下载
  119. -(void)resumeDownload{
  120. [_downloadTask resume];
  121. }
  122.  
  123. #pragma mark - 下载任务代理
  124. #pragma mark 下载中(会多次调用,可以记录下载进度)
  125. -(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
  126. [self setUIStatus:totalBytesWritten expectedToWrite:totalBytesExpectedToWrite];
  127. }
  128.  
  129. #pragma mark 下载完成
  130. -(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
  131. NSError *error;
  132. NSString *cachePath=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
  133. NSString *savePath=[cachePath stringByAppendingPathComponent:_textField.text];
  134. NSLog(@"%@",savePath);
  135. NSURL *saveUrl=[NSURL fileURLWithPath:savePath];
  136. [[NSFileManager defaultManager] copyItemAtURL:location toURL:saveUrl error:&error];
  137. if (error) {
  138. NSLog(@"Error is:%@",error.localizedDescription);
  139. }
  140. }
  141.  
  142. #pragma mark 任务完成,不管是否下载成功
  143. -(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
  144. [self setUIStatus:0 expectedToWrite:0];
  145. if (error) {
  146. NSLog(@"Error is:%@",error.localizedDescription);
  147. }
  148. }
  149. @end

演示效果:

NSURLSession支持程序的后台下载和上传,苹果官方将其称为进程之外的上传和下载,这些任务都是交给后台守护线程完成的,而非应用程序本身。即使文件在下载和上传过程中崩溃了也可以继续运行(注意如果用户强制退关闭应用程序,NSURLSession会断开连接)。下面看一下如何在后台进行文件下载,这在实际开发中往往很有效,例如在手机上缓存一个视频在没有网络的时候观看(为了简化程序这里不再演示任务的取消、挂起等操作)。下面对前面的程序稍作调整使程序能在后台完成下载操作:

  1. //
  2. // KCMainViewController.m
  3. // URLSession
  4. //
  5. // Created by Kenshin Cui on 14-03-23.
  6. // Copyright (c) 2014年 Kenshin Cui. All rights reserved.
  7. //
  8.  
  9. #import "KCMainViewController.h"
  10. #import "AppDelegate.h"
  11.  
  12. @interface KCMainViewController ()<NSURLSessionDownloadDelegate>{
  13. NSURLSessionDownloadTask *_downloadTask;
  14. NSString *_fileName;
  15. }
  16.  
  17. @end
  18.  
  19. @implementation KCMainViewController
  20.  
  21. #pragma mark - UI方法
  22. - (void)viewDidLoad {
  23. [super viewDidLoad];
  24.  
  25. [self downloadFile];
  26. }
  27.  
  28. #pragma mark 取得一个后台会话(保证一个后台会话,这通常很有必要)
  29. -(NSURLSession *)backgroundSession{
  30. static NSURLSession *session;
  31. static dispatch_once_t token;
  32. dispatch_once(&token, ^{
  33. NSURLSessionConfiguration *sessionConfig=[NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"com.cmjstudio.URLSession"];
  34. sessionConfig.timeoutIntervalForRequest=5.0f;//请求超时时间
  35. sessionConfig.discretionary=YES;//系统自动选择最佳网络下载
  36. sessionConfig.HTTPMaximumConnectionsPerHost=5;//限制每次最多一个连接
  37. //创建会话
  38. session=[NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];//指定配置和代理
  39. });
  40. return session;
  41. }
  42.  
  43. #pragma mark 文件下载
  44. -(void)downloadFile{
  45. _fileName=@"1.mp4";
  46. NSString *urlStr=[NSString stringWithFormat: @"http://192.168.1.208/FileDownload.aspx?file=%@",_fileName];
  47. urlStr =[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  48. NSURL *url=[NSURL URLWithString:urlStr];
  49. NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
  50.  
  51. //后台会话
  52. _downloadTask=[[self backgroundSession] downloadTaskWithRequest:request];
  53.  
  54. [_downloadTask resume];
  55. }
  56. #pragma mark - 下载任务代理
  57. #pragma mark 下载中(会多次调用,可以记录下载进度)
  58. -(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
  59. // [NSThread sleepForTimeInterval:0.5];
  60. // NSLog(@"%.2f",(double)totalBytesWritten/totalBytesExpectedToWrite);
  61. }
  62.  
  63. #pragma mark 下载完成
  64. -(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
  65. NSError *error;
  66. NSString *cachePath=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
  67. NSString *savePath=[cachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",[NSDate date]]];
  68. NSLog(@"%@",savePath);
  69. NSURL *saveUrl=[NSURL fileURLWithPath:savePath];
  70. [[NSFileManager defaultManager] copyItemAtURL:location toURL:saveUrl error:&error];
  71. if (error) {
  72. NSLog(@"didFinishDownloadingToURL:Error is %@",error.localizedDescription);
  73. }
  74. }
  75.  
  76. #pragma mark 任务完成,不管是否下载成功
  77. -(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
  78. if (error) {
  79. NSLog(@"DidCompleteWithError:Error is %@",error.localizedDescription);
  80. }
  81. }
  82. @end

运行上面的程序会发现即使程序退出到后台也能正常完成文件下载。为了提高用户体验,通常会在下载时设置文件下载进度,但是通过前面的介绍可以知道:当程序进入后台后,事实上任务是交给iOS系统来调度的,具体什么时候下载完成就不得而知,例如有个较大的文件经过一个小时下载完了,正常打开应用程序看到的此文件下载进度应该在100%的位置,但是由于程序已经在后台无法更新程序UI,而此时可以通过应用程序代理方法进行UI更新。具体原理如下图所示:

当NSURLSession在后台开启几个任务之后,如果有其中几个任务完成后系统会调用此应用程序的-(void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler代理方法;此方法会包含一个competionHandler(此操作表示应用完成所有处理工作),通常我们会保存此对象;直到最后一个任务完成,此时会重新通过会话标识(上面sessionConfig中设置的)找到对应的会话并调用NSURLSession的-(void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session代理方法,在这个方法中通常可以进行UI更新,并调用completionHandler通知系统已经完成所有操作。具体两个方法代码示例如下:

  1. -(void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler{
  2.  
  3. //backgroundSessionCompletionHandler是自定义的一个属性
  4. self.backgroundSessionCompletionHandler=completionHandler;
  5.  
  6. }
  7.  
  8. -(void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session{
  9. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  10.  
  11. //Other Operation....
  12.  
  13. if (appDelegate.backgroundSessionCompletionHandler) {
  14.  
  15. void (^completionHandler)() = appDelegate.backgroundSessionCompletionHandler;
  16.  
  17. appDelegate.backgroundSessionCompletionHandler = nil;
  18.  
  19. completionHandler();
  20.  
  21. }
  22. }

UIWebView

网络开发中还有一个常用的UI控件UIWebView,它是iOS中内置的浏览器控件,功能十分强大。如一些社交软件往往在应用程序内不需要打开其他浏览器就能看一些新闻之类的页面,就是通过这个控件实现的。需要注意的是UIWebView不仅能加载网络资源还可以加载本地资源,目前支持的常用的文档格式如:html、pdf、docx、txt等。

浏览器实现

下面将通过一个UIWebView开发一个简单的浏览器,界面布局大致如下:

在这个浏览器中将实现这样几个功能:

1.如果输入以”file://”开头的地址将加载Bundle中的文件

2.如果输入以“http”开头的地址将加载网络资源

3.如果输入内容不符合上面两种情况将使用bing搜索此内容

  1. //
  2. // KCMainViewController.m
  3. // UIWebView
  4. //
  5. // Created by Kenshin Cui on 14-3-22.
  6. // Copyright (c) 2014年 Kenshin Cui. All rights reserved.
  7. //
  8.  
  9. #import "KCMainViewController.h"'
  10. #define kFILEPROTOCOL @"file://"
  11.  
  12. @interface KCMainViewController ()<UISearchBarDelegate,UIWebViewDelegate>{
  13. UIWebView *_webView;
  14. UIToolbar *_toolbar;
  15. UISearchBar *_searchBar;
  16. UIBarButtonItem *_barButtonBack;
  17. UIBarButtonItem *_barButtonForward;
  18. }
  19.  
  20. @end
  21.  
  22. @implementation KCMainViewController
  23. #pragma mark - 界面UI事件
  24. - (void)viewDidLoad {
  25. [super viewDidLoad];
  26.  
  27. [self layoutUI];
  28. }
  29.  
  30. #pragma mark - 私有方法
  31. #pragma mark 界面布局
  32. -(void)layoutUI{
  33. /*添加地址栏*/
  34. _searchBar=[[UISearchBar alloc]initWithFrame:CGRectMake(0, 20, 320, 44)];
  35. _searchBar.delegate=self;
  36. [self.view addSubview:_searchBar];
  37.  
  38. /*添加浏览器控件*/
  39. _webView=[[UIWebView alloc]initWithFrame:CGRectMake(0, 64, 320, 460)];
  40. _webView.dataDetectorTypes=UIDataDetectorTypeAll;//数据检测,例如内容中有邮件地址,点击之后可以打开邮件软件编写邮件
  41. _webView.delegate=self;
  42. [self.view addSubview:_webView];
  43.  
  44. /*添加下方工具栏*/
  45. _toolbar=[[UIToolbar alloc]initWithFrame:CGRectMake(0, 524, 320, 44)];
  46. UIButton *btnBack=[UIButton buttonWithType:UIButtonTypeCustom];
  47. btnBack.bounds=CGRectMake(0, 0, 32, 32);
  48. [btnBack setImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
  49. [btnBack setImage:[UIImage imageNamed:@"back_disable.png"] forState:UIControlStateDisabled];
  50. [btnBack addTarget:self action:@selector(webViewBack) forControlEvents:UIControlEventTouchUpInside];
  51. _barButtonBack=[[UIBarButtonItem alloc]initWithCustomView:btnBack];
  52. _barButtonBack.enabled=NO;
  53.  
  54. UIBarButtonItem *btnSpacing=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
  55.  
  56. UIButton *btnForward=[UIButton buttonWithType:UIButtonTypeCustom];
  57. btnForward.bounds=CGRectMake(0, 0, 32, 32);
  58. [btnForward setImage:[UIImage imageNamed:@"forward.png"] forState:UIControlStateNormal];
  59. [btnForward setImage:[UIImage imageNamed:@"forward_disable.png"] forState:UIControlStateDisabled];
  60. [btnForward addTarget:self action:@selector(webViewForward) forControlEvents:UIControlEventTouchUpInside];
  61. _barButtonForward=[[UIBarButtonItem alloc]initWithCustomView:btnForward];
  62. _barButtonForward.enabled=NO;
  63.  
  64. _toolbar.items=@[_barButtonBack,btnSpacing,_barButtonForward];
  65. [self.view addSubview:_toolbar];
  66. }
  67. #pragma mark 设置前进后退按钮状态
  68. -(void)setBarButtonStatus{
  69. if (_webView.canGoBack) {
  70. _barButtonBack.enabled=YES;
  71. }else{
  72. _barButtonBack.enabled=NO;
  73. }
  74. if(_webView.canGoForward){
  75. _barButtonForward.enabled=YES;
  76. }else{
  77. _barButtonForward.enabled=NO;
  78. }
  79. }
  80. #pragma mark 后退
  81. -(void)webViewBack{
  82. [_webView goBack];
  83. }
  84. #pragma mark 前进
  85. -(void)webViewForward{
  86. [_webView goForward];
  87. }
  88. #pragma mark 浏览器请求
  89. -(void)request:(NSString *)urlStr{
  90. //创建url
  91. NSURL *url;
  92.  
  93. //如果file://开头的字符串则加载bundle中的文件
  94. if([urlStr hasPrefix:kFILEPROTOCOL]){
  95. //取得文件名
  96. NSRange range= [urlStr rangeOfString:kFILEPROTOCOL];
  97. NSString *fileName=[urlStr substringFromIndex:range.length];
  98. url=[[NSBundle mainBundle] URLForResource:fileName withExtension:nil];
  99. }else if(urlStr.length>0){
  100. //如果是http请求则直接打开网站
  101. if ([urlStr hasPrefix:@"http"]) {
  102. url=[NSURL URLWithString:urlStr];
  103. }else{//如果不符合任何协议则进行搜索
  104. urlStr=[NSString stringWithFormat:@"http://m.bing.com/search?q=%@",urlStr];
  105. }
  106. urlStr=[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];//url编码
  107. url=[NSURL URLWithString:urlStr];
  108.  
  109. }
  110.  
  111. //创建请求
  112. NSURLRequest *request=[NSURLRequest requestWithURL:url];
  113.  
  114. //加载请求页面
  115. [_webView loadRequest:request];
  116. }
  117.  
  118. #pragma mark - WebView 代理方法
  119. #pragma mark 开始加载
  120. -(void)webViewDidStartLoad:(UIWebView *)webView{
  121. //显示网络请求加载
  122. [UIApplication sharedApplication].networkActivityIndicatorVisible=true;
  123. }
  124.  
  125. #pragma mark 加载完毕
  126. -(void)webViewDidFinishLoad:(UIWebView *)webView{
  127. //隐藏网络请求加载图标
  128. [UIApplication sharedApplication].networkActivityIndicatorVisible=false;
  129. //设置按钮状态
  130. [self setBarButtonStatus];
  131. }
  132. #pragma mark 加载失败
  133. -(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
  134. NSLog(@"error detail:%@",error.localizedDescription);
  135. UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"系统提示" message:@"网络连接发生错误!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
  136. [alert show];
  137. }
  138.  
  139. #pragma mark - SearchBar 代理方法
  140. #pragma mark 点击搜索按钮或回车
  141. -(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
  142. [self request:_searchBar.text];
  143. }
  144. @end

运行效果:

其实UIWebView整个使用相当简单:创建URL->创建请求->加载请求,无论是加载本地文件还是Web内容都是这三个步骤。UIWebView内容加载事件同样是通过代理通知外界,常用的代理方法如开始加载、加载完成、加载出错等,这些方法通常可以帮助开发者更好的控制请求加载过程。

注意:UIWebView打开本地pdf、word文件依靠的并不是UIWebView自身解析,而是依靠MIME Type识别文件类型并调用对应应用打开。

UIWebView与页面交互

UIWebView与页面的交互主要体现在两方面:使用ObjC方法进行页面操作、在页面中调用ObjC方法两部分。和其他移动操作系统不同,iOS中所有的交互都集中于一个stringByEvaluatingJavaScriptFromString:方法中,以此来简化开发过程。

在iOS中操作页面

1.首先在request方法中使用loadHTMLString:加载了html内容,当然你也可以将html放到bundle或沙盒中读取并且加载。

2.然后在webViewDidFinishLoad:代理方法中通过stringByEvaluatingJavaScriptFromString: 方法可以操作页面中的元素,例如在下面的方法中读取了页面标题、修改了其中的内容。

  1. //
  2. // KCMainViewController.m
  3. // UIWebView
  4. //
  5. // Created by Kenshin Cui on 14-3-22.
  6. // Copyright (c) 2014年 Kenshin Cui. All rights reserved.
  7. //
  8.  
  9. #import "KCMainViewController.h"'
  10.  
  11. @interface KCMainViewController ()<UISearchBarDelegate,UIWebViewDelegate>{
  12. UIWebView *_webView;
  13. }
  14.  
  15. @end
  16.  
  17. @implementation KCMainViewController
  18. #pragma mark - 界面UI事件
  19. - (void)viewDidLoad {
  20. [super viewDidLoad];
  21.  
  22. [self layoutUI];
  23.  
  24. [self request];
  25. }
  26.  
  27. #pragma mark - 私有方法
  28. #pragma mark 界面布局
  29. -(void)layoutUI{
  30. /*添加浏览器控件*/
  31. _webView=[[UIWebView alloc]initWithFrame:CGRectMake(0, 20, 320, 548)];
  32. _webView.dataDetectorTypes=UIDataDetectorTypeAll;//数据检测类型,例如内容中有邮件地址,点击之后可以打开邮件软件编写邮件
  33. _webView.delegate=self;
  34. [self.view addSubview:_webView];
  35. }
  36. #pragma mark 浏览器请求
  37. -(void)request{
  38. //加载html内容
  39. NSString *htmlStr=@"<html>\
  40. <head><title>Kenshin Cui's Blog</title></head>\
  41. <body style=\"color:#0092FF;\">\
  42. <h1 id=\"header\">I am Kenshin Cui</h1>\
  43. <p>iOS 开发系列</p>\
  44. </body></html>";
  45.  
  46. //加载请求页面
  47. [_webView loadHTMLString:htmlStr baseURL:nil];
  48. }
  49.  
  50. #pragma mark - WebView 代理方法
  51. #pragma mark 开始加载
  52. -(void)webViewDidStartLoad:(UIWebView *)webView{
  53. //显示网络请求加载
  54. [UIApplication sharedApplication].networkActivityIndicatorVisible=true;
  55. }
  56.  
  57. #pragma mark 加载完毕
  58. -(void)webViewDidFinishLoad:(UIWebView *)webView{
  59. //隐藏网络请求加载图标
  60. [UIApplication sharedApplication].networkActivityIndicatorVisible=false;
  61.  
  62. //取得html内容
  63. NSLog(@"%@",[_webView stringByEvaluatingJavaScriptFromString:@"document.title"]);
  64. //修改页面内容
  65. NSLog(@"%@",[_webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('header').innerHTML='Kenshin Cui\\'s Blog'"]);
  66. }
  67. #pragma mark 加载失败
  68. -(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
  69. NSLog(@"error detail:%@",error.localizedDescription);
  70. UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"系统提示" message:@"网络连接发生错误!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
  71. [alert show];
  72. }
  73.  
  74. @end

运行效果:

页面中调用ObjC方法

页面中的js是无法直接调用ObjC方法的,但是可以变换一下思路:当需要进行一个js操作时让页面进行一个重定向,并且在重定向过程中传入一系列参数。在UIWebView的代理方法中有一个webView: shouldStartLoadWithRequest:navigationType方法,这个方法会在页面加载前执行,这样可以在这里拦截重定向,并且获取定向URL中的参数,根据这些参数约定一个方法去执行。

当访问百度搜索手机版时会发现,有时候点击页面中的某个元素可以调出iOS操作系统的UIActionSheet,下面不妨模拟一下这个过程。首先需要定义一个js方法,为了方便扩展,这个js保存在MyJs.js文件中存放到Bundle中,同时在页面中加载这个文件内容。MyJs.js内容如下:

  1. function showSheet(title,cancelButtonTitle,destructiveButtonTitle,otherButtonTitle) {
  2. var url='kcactionsheet://?';
  3. var paramas=title+'&'+cancelButtonTitle+'&'+destructiveButtonTitle;
  4. if(otherButtonTitle){
  5. paramas+='&'+otherButtonTitle;
  6. }
  7. window.location.href=url+ encodeURIComponent(paramas);
  8. }
  9. var blog=document.getElementById('blog');
  10. blog.onclick=function(){
  11. showSheet('系统提示','取消','确定',null);
  12. };

这个js的功能相当单一,调用showSheet方法则会进行一个重定向,调用过程中需要传递一系列参数,当然这些参数都是UIActionSheet中需要使用的,注意这里约定所有调用UIActionSheet的方法参数都以”kcactionsheet”开头。

然后在webView: shouldStartLoadWithRequest:navigationType方法中截获以“kcactionsheet”协议开头的请求,对于这类请求获得对应参数调用UIActionSheet。看一下完整代码:

  1. //
  2. // KCMainViewController.m
  3. // UIWebView
  4. //
  5. // Created by Kenshin Cui on 14-3-22.
  6. // Copyright (c) 2014年 Kenshin Cui. All rights reserved.
  7. //
  8.  
  9. #import "KCMainViewController.h"
  10.  
  11. @interface KCMainViewController ()<UISearchBarDelegate,UIWebViewDelegate>{
  12. UIWebView *_webView;
  13. }
  14.  
  15. @end
  16.  
  17. @implementation KCMainViewController
  18. #pragma mark - 界面UI事件
  19. - (void)viewDidLoad {
  20. [super viewDidLoad];
  21.  
  22. [self layoutUI];
  23.  
  24. [self request];
  25. }
  26.  
  27. #pragma mark - 私有方法
  28. #pragma mark 界面布局
  29. -(void)layoutUI{
  30. /*添加浏览器控件*/
  31. _webView=[[UIWebView alloc]initWithFrame:CGRectMake(0, 20, 320, 548)];
  32. _webView.dataDetectorTypes=UIDataDetectorTypeAll;//数据检测类型,例如内容中有邮件地址,点击之后可以打开邮件软件编写邮件
  33. _webView.delegate=self;
  34. [self.view addSubview:_webView];
  35. }
  36. #pragma mark 显示actionsheet
  37. -(void)showSheetWithTitle:(NSString *)title cancelButtonTitle:(NSString *)cancelButtonTitle destructiveButtonTitle:(NSString *)destructiveButtonTitle otherButtonTitles:(NSString *)otherButtonTitle{
  38. UIActionSheet *actionSheet=[[UIActionSheet alloc]initWithTitle:title delegate:nil cancelButtonTitle:cancelButtonTitle destructiveButtonTitle:destructiveButtonTitle otherButtonTitles:otherButtonTitle, nil];
  39. [actionSheet showInView:self.view];
  40. }
  41. #pragma mark 浏览器请求
  42. -(void)request{
  43. //加载html内容
  44. NSString *htmlStr=@"<html>\
  45. <head><title>Kenshin Cui's Blog</title></head>\
  46. <body style=\"color:#0092FF;\">\
  47. <h1 id=\"header\">I am Kenshin Cui</h1>\
  48. <p id=\"blog\">iOS 开发系列</p>\
  49. </body></html>";
  50.  
  51. //加载请求页面
  52. [_webView loadHTMLString:htmlStr baseURL:nil];
  53.  
  54. }
  55.  
  56. #pragma mark - WebView 代理方法
  57. #pragma mark 页面加载前(此方法返回false则页面不再请求)
  58. -(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
  59. if ([request.URL.scheme isEqual:@"kcactionsheet"]) {
  60. NSString *paramStr=request.URL.query;
  61. NSArray *params= [[paramStr stringByRemovingPercentEncoding] componentsSeparatedByString:@"&"];
  62. id otherButton=nil;
  63. if (params.count>3) {
  64. otherButton=params[3];
  65. }
  66. [self showSheetWithTitle:params[0] cancelButtonTitle:params[1] destructiveButtonTitle:params[2] otherButtonTitles:otherButton];
  67. return false;
  68. }
  69. return true;
  70. }
  71.  
  72. #pragma mark 开始加载
  73. -(void)webViewDidStartLoad:(UIWebView *)webView{
  74. //显示网络请求加载
  75. [UIApplication sharedApplication].networkActivityIndicatorVisible=true;
  76. }
  77.  
  78. #pragma mark 加载完毕
  79. -(void)webViewDidFinishLoad:(UIWebView *)webView{
  80. //隐藏网络请求加载图标
  81. [UIApplication sharedApplication].networkActivityIndicatorVisible=false;
  82.  
  83. //加载js文件
  84. NSString *path=[[NSBundle mainBundle] pathForResource:@"MyJs.js" ofType:nil];
  85. NSString *jsStr=[NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
  86. //加载js文件到页面
  87. [_webView stringByEvaluatingJavaScriptFromString:jsStr];
  88. }
  89. #pragma mark 加载失败
  90. -(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
  91. NSLog(@"error detail:%@",error.localizedDescription);
  92. UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"系统提示" message:@"网络连接发生错误!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
  93. [alert show];
  94. }
  95.  
  96. @end

运行效果:

网络状态

前面无论是下载还是上传都没有考虑网络状态,事实上实际开发过程中这个问题是不得不思考的,试想目前谁会用3G或4G网络下载一个超大的文件啊,因此实际开发过程中如果程序部署到了真机上必须根据不同的网络状态决定用户的操作,例如下图就是在使用QQ音乐播放在线音乐的提示:

网络状态检查在早期都是通过苹果官方的Reachability类进行检查(需要自行下载),但是这个类本身存在一些问题,并且官方后来没有再更新。后期大部分开发者都是通过第三方框架进行检测,在这里就不再使用官方提供的方法,直接使用AFNetworking框架检测。不管使用官方提供的类还是第三方框架,用法都是类似的,通常是发送一个URL然后去检测网络状态变化,网络改变后则调用相应的网络状态改变方法。下面是一个网络监测的简单示例:

  1. //
  2. // KCMainViewController.m
  3. // Network status
  4. //
  5. // Created by Kenshin Cui on 14-3-22.
  6. // Copyright (c) 2014年 Kenshin Cui. All rights reserved.
  7. //
  8.  
  9. #import "KCMainViewController.h"
  10. #import "AFNetworking.h"
  11.  
  12. @interface KCMainViewController ()<NSURLConnectionDataDelegate>
  13.  
  14. @end
  15.  
  16. @implementation KCMainViewController
  17.  
  18. #pragma mark - UI方法
  19. - (void)viewDidLoad {
  20. [super viewDidLoad];
  21.  
  22. [self checkNetworkStatus];
  23.  
  24. }
  25.  
  26. #pragma mark - 私有方法
  27. #pragma mark 网络状态变化提示
  28. -(void)alert:(NSString *)message{
  29. UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"System Info" message:message delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles: nil];
  30. [alertView show];
  31. }
  32.  
  33. #pragma mark 网络状态监测
  34. -(void)checkNetworkStatus{
  35. //创建一个用于测试的url
  36. NSURL *url=[NSURL URLWithString:@"http://www.apple.com"];
  37. AFHTTPRequestOperationManager *operationManager=[[AFHTTPRequestOperationManager alloc]initWithBaseURL:url];
  38.  
  39. //根据不同的网络状态改变去做相应处理
  40. [operationManager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
  41. switch (status) {
  42. case AFNetworkReachabilityStatusReachableViaWWAN:
  43. [self alert:@"2G/3G/4G Connection."];
  44. break;
  45. case AFNetworkReachabilityStatusReachableViaWiFi:
  46. [self alert:@"WiFi Connection."];
  47. break;
  48. case AFNetworkReachabilityStatusNotReachable:
  49. [self alert:@"Network not found."];
  50. break;
  51.  
  52. default:
  53. [self alert:@"Unknown."];
  54. break;
  55. }
  56. }];
  57.  
  58. //开始监控
  59. [operationManager.reachabilityManager startMonitoring];
  60. }
  61. @end

AFNetworking是网络开发中常用的一个第三方框架,常用的网络开发它都能帮助大家更好的实现,例如JSON数据请求、文件下载、文件上传(并且支持断点续传)等,甚至到AFNetworking2.0之后还加入了对NSURLSession的支持。由于本文更多目的在于分析网络操作原理,因此在此不再赘述,更多内容大家可以看官方文档,常用的操作都有示例代码。

iOS开发系列--网络开发的更多相关文章

  1. IOS开发之网络开发工具

    IOS开发之网络开发工具 做移动端开发  常常会涉及到几个模块:1.网络检測   2.网络请求get和post请求  3.文件上传  4.文件下载   5.断点续传 如今将这些一一分享给大家 ,也欢迎 ...

  2. iOS开发系列--并行开发其实很容易

    --多线程开发 概览 大家都知道,在开发过程中应该尽可能减少用户等待时间,让程序尽可能快的完成运算.可是无论是哪种语言开发的程序最终往往转换成汇编语言进而解释成机器码来执行.但是机器码是按顺序执行的, ...

  3. Spring Boot 开发系列一 开发环境的一些九九

    从今天开始写这个Spring Boot 开发系列,我是第二周学习JAVA的,公司号称springboot把JAVA的开发提升到填空的能力,本人是NET转JAVA的,想看看这个填空的东西到底有多强.废话 ...

  4. 移动开发在路上-- IOS移动开发系列 网络交互四(1)

    最近一段时间上班忙的没日没夜的,不是披星戴月,就是头天早上出门,第二天早上回家...一直没出处时间来更新博客,码农之苦,说了都是泪,废话不多说,直接本主题,经过之前三篇的讲述,ios开发的东西大家或多 ...

  5. iOS开发系列-网络状态监控

    概述 在网络应用中,需要对用户设别的网络状态进行实时监控,可以让用户了解自己的网络状态出现网络问题提示用户. 一般在网络状态不好的场景下需要做一些处理比如: WIFT/3G/4G网络:自动下载高清图. ...

  6. 移动开发在路上-- IOS移动开发系列 网络交互四(2)

    接着上次的讲,这次我们讲 网络请求的封装  打开创建的项目,让我们一起来继续完成他, 首先我们来创建一个NSobject 的文件 圈住出来的轻一点要注意.千万不要搞错了 创建好之后,开始编写代码, 我 ...

  7. iOS多线程与网络开发之发送接收server信息

    郝萌主倾心贡献,尊重作者的劳动成果,请勿转载. (1).使用同步方法发送get请求(不经常使用) 2 /** 发送get消息 */ 3 - (void) testGet { 4 NSString *r ...

  8. iOS多线程与网络开发之多线程NSThread

    郝萌主倾心贡献,尊重作者的劳动成果,请勿转载. 假设文章对您有所帮助,欢迎给作者捐赠,支持郝萌主,捐赠数额任意,重在心意^_^ 我要捐赠: 点击捐赠 Cocos2d-X源代码下载:点我传送 游戏官方下 ...

  9. iOS多线程与网络开发之多线程概述

    郝萌主倾心贡献,尊重作者的劳动成果,请勿转载. 假设文章对您有所帮助,欢迎给作者捐赠.支持郝萌主,捐赠数额任意,重在心意^_^ 我要捐赠: 点击捐赠 Cocos2d-X源代码下载:点我传送 游戏官方下 ...

随机推荐

  1. TODO:macOS编译PHP7.1

    TODO:macOS编译PHP7.1 本文主要介绍在macOS上编译PHP7.1,有兴趣的朋友可以去尝试一下. 1.下载PHP7.1源码,建议到PHP官网下载纯净到源码包php-7.1.0.tar.g ...

  2. Swift与C#的基础语法比较

    背景: 这两天不小心看了一下Swift的基础语法,感觉既然看了,还是写一下笔记,留个痕迹~ 总体而言,感觉Swift是一种前后端多种语言混合的产物~~~ 做为一名.NET阵营人士,少少多多总喜欢通过对 ...

  3. spark处理大规模语料库统计词汇

    最近迷上了spark,写一个专门处理语料库生成词库的项目拿来练练手, github地址:https://github.com/LiuRoy/spark_splitter.代码实现参考wordmaker ...

  4. ASP.NET 5 RC1 升级 ASP.NET Core 1.0 RC2 记录

    升级文档: Migrating from DNX to .NET Core Migrating from ASP.NET 5 RC1 to ASP.NET Core 1.0 RC2 Migrating ...

  5. Android -- 真正的 高仿微信 打开网页的进度条效果

    (本博客为原创,http://www.cnblogs.com/linguanh/) 目录: 一,为什么说是真正的高仿? 二,为什么要搞缓慢效果? 三,我的实现思路 四,代码,内含注释 五,使用方法与截 ...

  6. 谈一谈NOSQL的应用,Redis/Mongo

    1.心路历程 上年11月份来公司了,和另外一个同事一起,做了公司一个移动项目的微信公众号,然后为了推广微信公众号,策划那边需要我们做一些活动,包括抽奖,投票.最开始是没有用过redis的,公司因为考虑 ...

  7. Oracle学习之路-- 案例分析实现行列转换的几种方式

    注:本文使用的数据库表为oracle自带scott用户下的emp,dept等表结构. 通过一个例子来说明行列转换: 需求:查询每个部门中各个职位的总工资 按我们最原始的思路可能会这么写:       ...

  8. Java中的Socket的用法

                                   Java中的Socket的用法 Java中的Socket分为普通的Socket和NioSocket. 普通Socket的用法 Java中的 ...

  9. Java程序员:工作还是游戏,是该好好衡量一下了

    前阵子我终于下定决心,删掉了硬盘里所有的游戏. 身为一个程序猿,每天都要和各种新技术打交道,闲暇时间,总还得看一下各大论坛,逛逛博客园啥的,给自己充充电.游戏的话,其实我自小就比较喜欢,可以算是一种兴 ...

  10. Android之三种网络请求解析数据(最佳案例)

    AsyncTask解析数据 AsyncTask主要用来更新UI线程,比较耗时的操作可以在AsyncTask中使用. AsyncTask是个抽象类,使用时需要继承这个类,然后调用execute()方法. ...