AFN 数据上传下载

来源:互联网 发布:网站数据迁移方案 编辑:程序博客网 时间:2024/06/06 04:08

H:/0917/01_多线程_ViewController.m
[objc] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. /* 
  2. #import <UIKit/UIKit.h> 
  3. @interface ViewController : UIViewController 
  4. - (IBAction)click; 
  5. - (IBAction)click2; 
  6. @property (weak, nonatomic) IBOutlet UIImageView *imageView; 
  7. @end*/  
  8. //  ViewController.m  
  9. //  01-多线程  
  10. //  Created by apple on 13-9-17.  
  11. //  Copyright (c) 2013年 itcast. All rights reserved.  
  12. /* 
  13.  1.开启后台线程执行任务,最快捷的多线程,不需要自己管理线程 
  14.  [self performSelectorInBackground:@selector(test) withObject:nil]; 
  15.   
  16.  2.GCD 
  17.         方法名是sync,同步,肯定不会开线程,无论什么队列,全在主线程id=1 
  18.         方法名是async,异步,肯定开线程, 
  19.                             当队列是全局队列,开N条线程 
  20.                             当队列是创建的串行队列,只开1条线程 
  21.  1> 队列类型 
  22.  * 全局队列 
  23.    * 所有添加到全局队列中的任务都是并发执行(同时执行,可能会开启多个线程) 
  24.    * dispatch_get_global_queue 
  25.   
  26.  * 串行队列 
  27.    * 所有添加到串行队列中的任务都是按顺序执行(开一条线程)  
  28.      串行队列,要手动创建,前面是列队名,后面的NULL代表串行 
  29.    * dispatch_queue_create("myqueue", 0); 
  30.   
  31.  * 主队列 
  32.    * 只要添加到主队列中的任务都在主线程中执行(跟方法名没有关系)   
  33.    * dispatch_get_main_queue 
  34.   
  35.  2> 同步还是异步,取决于方法名(不会影响主队列,但影响全局队列、串行队列) 
  36.  * 同步:dispatch_sync,在当前线程执行任务,不会开启新的线程 
  37.  * 异步:dispatch_async,在其他线程执行任务,会开启新的线程 
  38.   
  39.  3.NSOperation\NSOperationQueue 
  40.  1> 使用步骤 
  41.  * 创建NSOperation 
  42.  * 添加NSOperation到NSOperationQueue,会自动启动 
  43.  * 设置OperationQueue队列的同一时间最大并发执行的线程个数 
  44.   
  45.  2> 优点 
  46.    * 更加面向对象 
  47.    * 可以控制最大并发数  maxConcurrentOperationCount 
  48.    * 添加任务(Operation)之间的依赖 addDependency  
  49.      比如,先下载图片,之后才对图片滤镜美化工作,*/   
  50. #import "ViewController.h"  
  51. @interface ViewController ()  
  52. {  
  53.     NSOperationQueue *_queue;  
  54. }  
  55. @end  
  56. @implementation ViewController  
  57. - (void)viewDidLoad  
  58. {  
  59.     [super viewDidLoad];  
  60.     // 实例化操作队列NSOperationQueue  
  61.     _queue = [[NSOperationQueue alloc] init];  
  62.     // 设置操作队列的最大并发数:2  
  63.     _queue.maxConcurrentOperationCount = 2;  
  64. }  
  65.   
  66. - (IBAction)click {  
  67.     // 操作1:NSBlockOperation  
  68.     NSOperation *op = [NSBlockOperation blockOperationWithBlock:^{  
  69.         NSLog(@"下载645645645645645-%@", [NSThread currentThread]);  
  70.     }];  
  71.     // 操作2:NSOperation  
  72.     NSOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{  
  73.         NSLog(@"滤镜-%@", [NSThread currentThread]);  
  74.     }];  
  75.     // op2依赖于op(op执行完,才能执行op2),如先下载图片,再进行美化操作  
  76.     [op2 addDependency:op];  
  77.     // 添加操作1到操作队列,(会自动开启)  
  78.     [_queue addOperation:op];  
  79.     // 添加操作1到操作队列,(会自动开启)  
  80.     [_queue addOperation:op2];  
  81.     //------------------1次添加20个操作到操作队列------------------  
  82.     for (int i = 0; i<20; i++) {  
  83.         NSOperation *op = [NSBlockOperation blockOperationWithBlock:^{  
  84.             NSLog(@"下载图片-%@", [NSThread currentThread]);  
  85.         }];  
  86.         [_queue addOperation:op];  
  87.     }  
  88.     //-------------异步全局队列,下载图片,完毕后回到主线程----------------  
  89.     dispatch_async(dispatch_get_global_queue  
  90.                             (DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{  
  91.         NSLog(@"下载图片-%@", [NSThread currentThread]);  
  92.         UIImage *image = nil;  
  93.         // 下载完毕,想回到主线程,更新UI界面,同步或异步,只要是主线程队列  
  94.         dispatch_sync(dispatch_get_main_queue(), ^{  
  95.             _imageView.image = image;  
  96.             NSLog(@"刷新ImageView-%@", [NSThread currentThread]);  
  97.         });  
  98.         // 下载完毕,也可以在主线程中执行方法setImage:,参数是:image  
  99.         [_imageView performSelectorOnMainThread:@selector(setImage:)   
  100.                                 withObject:image waitUntilDone:YES];  
  101.     });  
  102. }  
  103. - (IBAction)click2 {  
  104.     NSLog(@"click2-%@", [NSThread currentThread]);  
  105.     // performSelectorInBackground最快捷的多线程,不需要自己管理线程  
  106.     [self performSelectorInBackground:@selector(test) withObject:nil];      
  107.     // GCD的三种队列之:全局队列 global_queue  
  108.     dispatch_queue_t queue =   
  109.                   dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);  
  110.     // GCD的三种队列之:串行队列 要手动创建queue_create,第2个参数0即串行  
  111.     dispatch_queue_t queue = dispatch_queue_create("myqueue"0);  
  112.       
  113.     dispatch_sync(queue, ^{ // 耗时操作  
  114.         NSLog(@"dispatch_async-%@", [NSThread currentThread]);  
  115.     });  
  116.     dispatch_sync(queue, ^{ // 耗时操作  
  117.         NSLog(@"dispatch_async-%@", [NSThread currentThread]);  
  118.     });  
  119.     dispatch_sync(queue, ^{ // 耗时操作  
  120.         NSLog(@"dispatch_async-%@", [NSThread currentThread]);  
  121.     });  
  122.       
  123.     // C框架中,只要create copy都要release  
  124.     // dispatch_release(queue);  
  125. }  
  126.   
  127. - (void)test  
  128. {  
  129.     for (int i = 0; i<900000; i++) {  
  130.         NSString *str = [NSString stringWithFormat:@"fsdfsdfdsf----%d", i];  
  131.         str = [str stringByAppendingString:@"fsdgdfgdf"];  
  132.     }  
  133.     NSLog(@"test-%@", [NSThread currentThread]);  
  134. }  
  135. @end  

H:/0917/02_GET_VideosViewController.m
[objc] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. //  VideosViewController.m  
  2. //  02-网络请求  
  3. //  Created by apple on 13-9-17.  
  4. //  Copyright (c) 2013年 itcast. All rights reserved.  
  5. /* 
  6.     VideosViewController,继承自表格控制器 
  7.     用于接收,从上一个控制器,传递过来的数据,进行列表显示 
  8. */  
  9. #import "VideosViewController.h"  
  10. @interface VideosViewController : UITableViewController  
  11. @property (nonatomicstrongNSArray *videos;  
  12. @end  
  13. @implementation VideosViewController  
  14. #pragma mark - Table view data source  
  15. - (NSInteger)tableView:(UITableView *)tableView   
  16.                         numberOfRowsInSection:(NSInteger)section  
  17. {  
  18.     return _videos.count;  
  19. }  
  20. - (UITableViewCell *)tableView:(UITableView *)tableView   
  21.                     cellForRowAtIndexPath:(NSIndexPath *)indexPath  
  22. {  
  23.     // 优化固定写法  
  24.     static NSString *CellIdentifier = @"Cell";  
  25.     UITableViewCell *cell = [tableView  
  26.                         dequeueReusableCellWithIdentifier:CellIdentifier];  
  27.     if (cell == nil) {  
  28.         cell = [[UITableViewCell alloc] initWithStyle:  
  29.                 UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];  
  30.     }  
  31.     // 取出字典  
  32.     NSDictionary *video = _videos[indexPath.row];  
  33.     // 设置独一无二的数据  
  34.     cell.textLabel.text = video[@"name"];  
  35.     cell.detailTextLabel.text = [NSString stringWithFormat:@"时长:%@", video[@"length"]];  
  36.     return cell;  
  37. }  
  38. @end  

H:/0917/02_GET_ViewController.m
[objc] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. //  ViewController.m  
  2. //  02-网络请求  
  3. //  Created by apple on 13-9-17.  
  4. //  Copyright (c) 2013年 itcast. All rights reserved.  
  5. /* 
  6.  1.向HTTP服务器发送请求 
  7.  1> GET 
  8.  * 所有参数拼接在URL后面 
  9.  * 路径如果包含了中文等字符,需要进行转码  
  10.    [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] 
  11.   
  12.  2> POST 
  13.  * 参数不拼接在URL后面 
  14.  * 参数放在请求体里面(body),参数包含了中文,还是需要转码 
  15.   
  16.  2.异步\同步请求 
  17.  1> 同步请求,sendSynchronousRequest,直接拿到服务器返回的数据 
  18.  * NSData *data = [NSURLConnection sendSynchronousRequest:request  
  19.                                 returningResponse:nil error:nil] 
  20.   
  21.  2> 异步请求,sendAsynchronousRequest,返回的数据在response里面 
  22.  1) [NSURLConnection sendAsynchronousRequest:request  
  23.                 queue:<#(NSOperationQueue *)#>  
  24.                 completionHandler:^(NSURLResponse *, NSData *, NSError *) { 
  25.   
  26.      }]; 
  27.   
  28.  2) connectionWithRequest,代理负责接收服务器返回的数据 
  29.     NSURLConnection *conn = [NSURLConnection connectionWithRequest:request 
  30.                                                 delegate:self]; 
  31.     // 必须手动启动连接,默认就是异步请求 
  32.     [conn start]; 
  33.      
  34.      
  35.     实现代理方法:接收服务器返回的数据,并且解析数据 
  36.  接收服务器的数据时调用(可多次调用) 
  37.  - (void)connection:(NSURLConnection *)connection  
  38.                     didReceiveData:(NSData *)data 
  39.  { 
  40.     // 这个代理方法里面,只需要拼接数据即可 
  41.     [_allData appendData:data]; 
  42.  } 
  43.   
  44.  数据接收完毕,就会调用,这儿可以正式解析返回的数据 
  45.  - (void)connectionDidFinishLoading:(NSURLConnection *)connection {} 
  46.  */  
  47. #import "ViewController.h"  
  48. // 拿到服务器返回的视频列表数据后,要跳到VideosViewController界面去显示  
  49. #import "VideosViewController.h"  
  50. @interface ViewController () <NSURLConnectionDataDelegate>  
  51. {  
  52.     // URLConnection的代理方法didReceiveData中,拼接接收到的服务器的数据  
  53.     NSMutableData *_allData;  
  54. }  
  55. @property (weak, nonatomic) IBOutlet UITextField *username;  
  56. @property (weak, nonatomic) IBOutlet UITextField *pwd;  
  57. @end  
  58. @implementation ViewController  
  59. // 响应按钮点击,登录  
  60. - (IBAction)login0 {  
  61.     // 1.请求参数,用户名密码  
  62.     NSString *username = _username.text;  
  63.     NSString *pwd = _pwd.text;  
  64.     // 2.拼接URL  
  65.     NSString *url = [NSString stringWithFormat:@"http://169.254.109.85:8080/MJServer/login?username=%@&pwd=%@", username, pwd];  
  66.     // 对URL中的中文转码  
  67.     url = [url stringByAddingPercentEscapesUsingEncoding:  
  68.                                         NSUTF8StringEncoding];  
  69.     // 通过url创建 请求对象request  
  70.     NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL   
  71.                                             URLWithString:url]];  
  72.     // 3.NSURLConnection发送同步请求,并获得服务器返回的数据(同步请求)  
  73.     NSData *data = [NSURLConnection sendSynchronousRequest:request  
  74.                                     returningResponse:nil error:nil];  
  75.     // 3.NSURLConnection发送异步请求,不返回值  
  76.     [NSURLConnection sendAsynchronousRequest:request  
  77.                 queue:<#(NSOperationQueue *)#>  
  78.                 completionHandler:^(NSURLResponse *, NSData *, NSError *) {  
  79.                 // 服务器返回的内容在response里面  
  80.     }];  
  81.     // 4.解析服务器返回的JSON数据  
  82.     NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data  
  83.                             options:NSJSONReadingMutableLeaves error:nil];  
  84.     // 5.如果用户名和密码错误,返回的Json中包含error  
  85.     NSString *error = result[@"error"];  
  86.     if (error) {   
  87.         UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"  
  88.                         message:error delegate:nil cancelButtonTitle:@"好的"  
  89.                         otherButtonTitles:nil, nil nil];  
  90.         // 显示UIAlertView  
  91.         [alert show];  
  92.     } else {  
  93.         NSLog(@"登录成功-%@", result[@"videos"]);  
  94.     }  
  95. }  
  96. // 响应按钮点击,登录  
  97. - (IBAction)login {  
  98.     // 1.获取输入框的用户名和密码  
  99.     NSString *username = _username.text;  
  100.     NSString *pwd = _pwd.text;  
  101.     // 2.拼接url  
  102.     NSString *url = [NSString stringWithFormat:@"http://169.254.109.85:8080/MJServer/login?username=%@&pwd=%@", username, pwd];  
  103.     // 重要!!!!URL参数中的中文必须转码  
  104.     url = [url stringByAddingPercentEscapesUsingEncoding:  
  105.                                     NSUTF8StringEncoding];  
  106.     // 根据url创建 请求对象request  
  107.     NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL   
  108.                                             URLWithString:url]];  
  109.     // 3.通过request创建Connection对象,并且设置URLConnection的代理  
  110.     NSURLConnection *conn = [NSURLConnection connectionWithRequest:request  
  111.                                                     delegate:self];  
  112.     // 4.手动启动Connection,默认就是异步请求,其他交给代理处理  
  113.     [conn start];  
  114.     _allData = [NSMutableData data];  
  115. }  
  116. #pragma mark URLConnection的代理方法,接收到服务器的数据时调用(可能多次调用)  
  117. - (void)connection:(NSURLConnection *)connection   
  118.                     didReceiveData:(NSData *)data  
  119. {  
  120.     // 在代理方法didReceiveData,只需要拼接字符串即可  
  121.     [_allData appendData:data];  
  122. }  
  123. #pragma mark URLConnection的代理方法,数据接收完毕,就会调用  
  124. - (void)connectionDidFinishLoading:(NSURLConnection *)connection  
  125. {  
  126.     // 4.解析服务器返回的JSON  
  127.     NSDictionary *result = [NSJSONSerialization JSONObjectWithData:_allData  
  128.                              options:NSJSONReadingMutableLeaves error:nil];  
  129.     // 5.如果用户名和密码错误,返回数据就会包含error  
  130.     NSString *error = result[@"error"];  
  131.     if (error) {  
  132.         UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"   
  133.                     message:error delegate:nil cancelButtonTitle:@"好的"  
  134.                                             otherButtonTitles:nil, nil nil];  
  135.         [alert show];  
  136.     } else {  
  137.         // 跳到视频列表界面,performSegueWithIdentifier,list是SB中连线设置的  
  138.         [self performSegueWithIdentifier:@"list" sender:result[@"videos"]];  
  139.     }  
  140. }  
  141. // 为跳到下一个控制器,作准备,实质是把上面的参数sender传递到下面方法sender  
  142. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender  
  143. {  
  144.     // VideosViewController是要跳至的目标控制器,继承成tableViewController  
  145.     VideosViewController *videosVC = segue.destinationViewController;  
  146.     // 成员数组,记住当前控制器从服务器要回来的数据,result[@"videos"]  
  147.     videosVC.videos = sender;  
  148. }  
  149. @end  

H:/0917/03_POST_VideosViewController.m
[objc] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. //  VideosViewController.m  
  2. //  02-网络请求  
  3. //  Created by apple on 13-9-17.  
  4. //  Copyright (c) 2013年 itcast. All rights reserved.  
  5. /* 
  6. #import <UIKit/UIKit.h> 
  7. @interface VideosViewController : UITableViewController 
  8. @property (nonatomic, strong) NSArray *videos; 
  9. @end 
  10. */  
  11. #import "VideosViewController.h"  
  12. @interface VideosViewController ()  
  13. @end  
  14. @implementation VideosViewController  
  15. #pragma mark - Table view data source  
  16. - (NSInteger)tableView:(UITableView *)tableView  
  17.                         numberOfRowsInSection:(NSInteger)section  
  18. {  
  19.     return _videos.count;  
  20. }  
  21. - (UITableViewCell *)tableView:(UITableView *)tableView  
  22.                     cellForRowAtIndexPath:(NSIndexPath *)indexPath  
  23. {  
  24.     static NSString *CellIdentifier = @"Cell";  
  25.     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];  
  26.     if (cell == nil) {  
  27.         cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];  
  28.     }  
  29.     NSDictionary *video = _videos[indexPath.row];  
  30.     cell.textLabel.text = video[@"name"];  
  31.     cell.detailTextLabel.text = [NSString stringWithFormat:@"时长:%@", video[@"length"]];  
  32.     return cell;  
  33. }  
  34. @end  

H:/0917/03_POST_ViewController.m
[objc] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. //  ViewController.m  
  2. //  02-网络请求  
  3. //  Created by apple on 13-9-17.  
  4. //  Copyright (c) 2013年 itcast. All rights reserved.  
  5. /* 
  6. #import <UIKit/UIKit.h> 
  7. @interface ViewController : UIViewController 
  8. @property (weak, nonatomic) IBOutlet UITextField *username; 
  9. @property (weak, nonatomic) IBOutlet UITextField *pwd; 
  10. - (IBAction)login; 
  11. @end 
  12. */  
  13. /* 
  14.  1.向HTTP服务器发送请求 
  15.  1> GET 
  16.  * 所有参数拼接在URL后面 
  17.  * 路径如果包含了中文等字符,需要进行转码  
  18.    [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] 
  19.   
  20.  2> POST 
  21.  * 参数不拼接在URL后面 
  22.  * 参数放在请求体里面(body),参数包含了中文,还是需要转码 
  23.   
  24.  2.异步\同步请求 
  25.  1> 同步请求 
  26.  * NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil] 
  27.   
  28.  2> 异步请求 
  29.  1) [NSURLConnection sendAsynchronousRequest:request queue:<#(NSOperationQueue *)#> completionHandler:^(NSURLResponse *, NSData *, NSError *) { 
  30.   
  31.      }]; 
  32.   
  33.  2) NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self]; 
  34.     // 默认就是异步请求 
  35.     [conn start]; 
  36.     实现代理方法:接收服务器返回的数据,并且解析数据 
  37.  #pragma mark 接收到服务器的数据时就会调用一次(可能会调用多次) 
  38.  - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
  39.  { 
  40.     [_allData appendData:data]; 
  41.  } 
  42.   
  43.  #pragma mark 请求结束(数据接收完毕)就会调用 
  44.  - (void)connectionDidFinishLoading:(NSURLConnection *)connection {} 
  45.  */  
  46. #import "ViewController.h"  
  47. #import "VideosViewController.h"  
  48. @interface ViewController () <NSURLConnectionDataDelegate>  
  49. {  
  50.     NSMutableData *_allData;  
  51. }  
  52. @end  
  53. @implementation ViewController  
  54. - (IBAction)login {  
  55.     // 1.获取输入框内容  
  56.     NSString *username = _username.text;  
  57.     NSString *pwd = _pwd.text;  
  58.     // 2.post的请求路径  
  59.     NSString *url = [NSString stringWithFormat:  
  60.                     @"http://169.254.178.47:8080/MJServer/login"];   
  61.     // 通过url创建MutableURLRequest,post专用请求  
  62.     NSMutableURLRequest *request = [NSMutableURLRequest  
  63.                             requestWithURL:[NSURL URLWithString:url]];  
  64.     // 必须指定请求方法:POST,大小写无关  
  65.     request.HTTPMethod = @"POST";  
  66.     // 请求体HTTPBody,中文依然必须转码  
  67.     NSString *param = [NSString stringWithFormat:@"username=%@&pwd=%@",  
  68.                                                  username, pwd];  
  69.     request.HTTPBody = [param dataUsingEncoding:NSUTF8StringEncoding];  
  70.     // 3.发送异步请求,设置代理为当前控制器,默认就是异步请求  
  71.     NSURLConnection *conn = [NSURLConnection connectionWithRequest:request  
  72.                             delegate:self];  
  73.     // 4.必须手动开启conn  
  74.     [conn start];  
  75.     _allData = [NSMutableData data];  
  76. }  
  77. #pragma mark 接收到服务器的数据时就会调用一次(可能会调用多次)  
  78. - (void)connection:(NSURLConnection *)connection   
  79.                 didReceiveData:(NSData *)data  
  80. {  
  81.     // 唯一作用就是,拼接数据  
  82.     [_allData appendData:data];  
  83. }  
  84. #pragma mark 请求结束(数据接收完毕)就会调用  
  85. - (void)connectionDidFinishLoading:(NSURLConnection *)connection  
  86. {  
  87.     // 4.解析服务器返回的JSON  
  88.     NSDictionary *result = [NSJSONSerialization JSONObjectWithData:_allData  
  89.                             options:NSJSONReadingMutableLeaves error:nil];  
  90.     // 5.数据处理  
  91.     NSString *error = result[@"error"];  
  92.     if (error) { // 如果有错误  
  93.         UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"  
  94.                     message:error delegate:nil cancelButtonTitle:@"好的"  
  95.                                             otherButtonTitles:nil, nil nil];  
  96.         [alert show];  
  97.     } else {  
  98.         // 跳到视频列表界面,performSegueWithIdentifier,list是sb中连线指定的  
  99.         [self performSegueWithIdentifier:@"list" sender:result[@"videos"]];  
  100.     }  
  101. }  
  102. // 为跳至下一个控制之前,作准备,即填充数据,sender是上面传到这儿的,即result[@"videos"]  
  103. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender  
  104. {  
  105.     // 1,先导入头文件,实例化要跳转的目标控制器,并为其成员数组赋值,即result[@"videos"]  
  106.     VideosViewController *videosVC = segue.destinationViewController;  
  107.     videosVC.videos = sender;  
  108. }  
  109. @end  

H:/0917/04_AFN_ViewController.m
[objc] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. //  ViewController.m  
  2. //  04-AFN框架使用,因为ASI已停止更新~  
  3. //  Created by apple on 13-9-17.  
  4. /* 
  5.     AFN依赖3个框架 
  6.     security.framework 
  7.     systemConfiguration.framework 
  8.     mobileCoreServices.framework 
  9. */    
  10. #import "ViewController.h"  
  11. #import "AFNetworking.h"  
  12. @interface ViewController ()  
  13. @end  
  14. @implementation ViewController  
  15. - (IBAction)click {  
  16.     // 1.设置baseURL路径,域名  
  17.     NSURL *baseURL = [NSURL URLWithString:  
  18.                             @"http://169.254.178.47:8080/MJServer"];  
  19.     // 通过baseURL创建AFN客户端                          
  20.     AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:baseURL];  
  21.     // 2.封装请求,多态,因返回URLMutableRequest,参数:方式,路径,请求参数为字典  
  22.     NSURLRequest *request = [client requestWithMethod:@"POST"   
  23.                             path:@"login" parameters:@{  
  24.                              @"username" : @"母鸡",  
  25.                              @"pwd" : @"124353"  
  26.      }];  
  27.     // 3.通过block构造AFHTTPRequestOperation  
  28.     AFHTTPRequestOperation *operation =   
  29.             [client HTTPRequestOperationWithRequest:request  
  30.             success:^(AFHTTPRequestOperation *operation, id responseObject) {  
  31.         // 成功后,解析服务器返回的数据     
  32.         NSDictionary *json = [NSJSONSerialization   
  33.                             JSONObjectWithData:responseObject   
  34.                             options:NSJSONReadingMutableLeaves error:nil];  
  35.         NSLog(@"%@", json);  
  36.     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {  
  37.         // 失败后,dosomething...  
  38.     }];  
  39.     // 手动开启AFHTTPRequestOperation  
  40.     [operation start];  
  41. }  
  42. @end  

H:/0917/05_下载_ViewController.m
[objc] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. //  ViewController.m  
  2. //  05-文件下载  
  3. //  Created by apple on 13-9-17.  
  4. /* 
  5.     AFN依赖3个框架 
  6.     security.framework 
  7.     systemConfiguration.framework 
  8.     mobileCoreServices.framework 
  9.  
  10. #import <UIKit/UIKit.h> 
  11. @interface ViewController : UIViewController 
  12. - (IBAction)download; 
  13. @property (weak, nonatomic) IBOutlet UIProgressView *progressView; 
  14. @property (weak, nonatomic) IBOutlet UIImageView *imageView; 
  15. @end 
  16. */  
  17. #import "ViewController.h"  
  18. // 需导入第3方框架  
  19. #import "AFNetworking.h"  
  20. @interface ViewController () <NSURLConnectionDataDelegate>  
  21. {  
  22.     // 唯一作用,拼接数据  
  23.     NSMutableData *_imgData;  
  24.     // Content-Length  
  25.     int _imgTotalLength;  
  26. }  
  27. @end  
  28. @implementation ViewController  
  29. /* 
  30.     下载图片方式一 
  31.     使用默认的NSURLRequest即GET方式下载图片,见方法 defaultDownLoad 
  32.     其中设置了代理为当前控制器,遵守协议,处理以下方法: 
  33.     didReceiveResponse,从response中head字典中取出:Content-Length 
  34.     didReceiveData,唯一作用,拼接数据,更新进度 
  35.     connectionDidFinishLoading,下载图片完毕,设置imageView 
  36. */  
  37. - (void) defaultDownLoad  
  38. {  
  39.     // 使用默认的NSURLRequest即GET方式下载图片  
  40.     _imgData = [NSMutableData data];  
  41.     NSURLConnection *conn = [NSURLConnection   
  42.                     connectionWithRequest:[NSURLRequest  
  43.                     requestWithURL:[NSURL   
  44.                     URLWithString:@"http://169.254.178.47:8080/MJServer/lufy.png"]]   
  45.                     delegate:self];  
  46.     [conn start];  
  47. }  
  48. #pragma mark 开始接到服务器的响应就会调用  
  49. - (void)connection:(NSURLConnection *)connection   
  50.             didReceiveResponse:(NSURLResponse *)response  
  51. {  
  52.     // 将URLResponse转成子类HTTPURLResponse  
  53.     NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;  
  54.     // 从response中head字典中取出:Content-Length  
  55.     _imgTotalLength = [httpResponse.allHeaderFields[@"Content-Length"]  
  56.                        intValue];  
  57. }  
  58. #pragma mark 接收到服务器返回的数据时调用,可多次调用  
  59. - (void)connection:(NSURLConnection *)connection   
  60.                     didReceiveData:(NSData *)data  
  61. {  
  62.     // 唯一作用,拼接数据  
  63.     [_imgData appendData:data];  
  64.     // 更新进度  
  65.     _progressView.progress = (double)_imgData.length / _imgTotalLength;  
  66. }  
  67. #pragma mark 服务器的数据接收完毕就会调用  
  68. - (void)connectionDidFinishLoading:(NSURLConnection *)connection  
  69. {  
  70.     NSLog(@"下载完毕");  
  71.     // 将图片data设置在imageView上面  
  72.     _imageView.image = [UIImage imageWithData:_imgData];  
  73. }  
  74.   
  75.   
  76. //--------------------下载图片方式二:使用AFN下载图片,getPath更直接简洁  
  77. // 响应点击,开始下载图片data  
  78. - (IBAction)download {  
  79.     // 1.设置baseUrl路径  
  80.     NSURL *baseURL = [NSURL URLWithString:@"http://169.254.178.47:8080/MJServer"];  
  81.     // 2.根据baseURL,构建AFHTTPClient  
  82.     AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:baseURL];  
  83.     // 3.AFHTTPClient的getPath方法,GET请求,如果是POST只改方法名即可  
  84.     [client getPath:@"lufy.png" parameters:nil   
  85.             success:^(AFHTTPRequestOperation *operation, id responseObject) {  
  86.         // 下载成功,设置imageView  
  87.         _imageView.image = [UIImage imageWithData:responseObject];  
  88.     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {  
  89.         // 失败时,调用  
  90.     }];      
  91. }  
  92. //--------------------下载图片方式三:使用AFN下载图片,不用代理,一个方法搞定  
  93. - (void)test  
  94. {     
  95.     // 1.设置baseurl路径  
  96.     NSURL *baseURL = [NSURL URLWithString:@"http://169.254.178.47:8080/MJServer"];  
  97.     AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:baseURL];  
  98.     // 2.requestWithMethod:path:方法 封装URLRequest请求  
  99.     NSURLRequest *request = [client requestWithMethod:@"GET"  
  100.                             path:@"lufy.png" parameters:nil];  
  101.     // 3.通过请求,构造AFHTTPRequestOperation  
  102.     AFHTTPRequestOperation *operation = [client  
  103.                 HTTPRequestOperationWithRequest:request  
  104.                 success:^(AFHTTPRequestOperation *operation,   
  105.                 id responseObject) {  
  106.         // 下载成功,设置imageView  
  107.         _imageView.image = [UIImage imageWithData:responseObject];  
  108.     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {  
  109.         // 失败时,调用   
  110.     }];  
  111.     // 4.手动开启AFHTTPRequestOperation  
  112.     [operation start];  
  113.     // 5.设置监听器,监听下载进度  
  114.     // bytesRead 当前传递的字节数  
  115.     // totalBytesRead 已经传递的总字节数  
  116.     // totalBytesExpectedToRead 总长度  
  117.     [operation setDownloadProgressBlock:^(NSUInteger bytesRead,   
  118.             long long totalBytesRead, long long totalBytesExpectedToRead) {  
  119.         _progressView.progress = (double)totalBytesRead/totalBytesExpectedToRead;  
  120.     }];  
  121. }  
  122. @end  

H:/0917/06_上传_ViewController.m
[objc] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. //  ViewController.m  
  2. //  06-文件上传  
  3. //  Created by apple on 13-9-17.  
  4. /* 
  5. 将Xcode中的文件,弄到模拟器里面去,android是Push 
  6. iOS中用代码:UIImageWriteToSavedPhotoAlbum([UIImage imageNamed:@"1.jpg"],nil,nil,nil); 
  7.  
  8. #import <UIKit/UIKit.h> 
  9. @interface ViewController : UIViewController 
  10. @property (weak, nonatomic) IBOutlet UIImageView *imageView; 
  11. - (IBAction)getPhoto; 
  12. - (IBAction)upload; 
  13. @end 
  14. */  
  15. #import "ViewController.h"  
  16. #import "AFNetworking.h"  
  17. @interface ViewController () <UIActionSheetDelegate,  
  18.             UINavigationControllerDelegate, UIImagePickerControllerDelegate>  
  19. @end  
  20. @implementation ViewController  
  21. // 响应按钮点击,选取要上传的相片  
  22. - (IBAction)getPhoto {  
  23.     // 构造并弹出UIActionSheet动作列表,供用户选择相片来源  
  24.     UIActionSheet *sheet = [[UIActionSheet alloc]  
  25.                 initWithTitle:@"请选择图片" delegate:self  
  26.                 cancelButtonTitle:@"取消" destructiveButtonTitle:nil  
  27.                 otherButtonTitles:@"拍照"@"相册", nil nil];  
  28.     [sheet showInView:self.view.window];  
  29. }  
  30. // UIActionSheet的代理方法,当用户点击了动作列表中的某个按钮时候调用  
  31. - (void)actionSheet:(UIActionSheet *)actionSheet  
  32.             clickedButtonAtIndex:(NSInteger)buttonIndex  
  33. {  
  34.     // 实例化照片选择器,UIImagePickerController,并根据按钮索引设置相片来源  
  35.     UIImagePickerController *vc = [[UIImagePickerController alloc] init];  
  36.     switch (buttonIndex) {  
  37.         case 0// 拍照  
  38.             vc.sourceType = UIImagePickerControllerSourceTypeCamera;  
  39.             break;  
  40.         case 1// 相册  
  41.             vc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;  
  42.             break;  
  43.         default:  
  44.             break;  
  45.     }  
  46.     // 设置ImagePickerController的代理为当前控制器,处理选择相片之后的事件  
  47.     vc.delegate = self;  
  48.     // 展示相片选择控制器  
  49.     [self presentViewController:vc animated:YES completion:nil];  
  50. }  
  51. #pragma mark ImagePickerController的代理方法,拍照完毕或从相册中取完相片时调用  
  52. - (void)imagePickerController:(UIImagePickerController *)picker  
  53.                     didFinishPickingMediaWithInfo:(NSDictionary *)info  
  54. {  
  55.     // 获取源图  
  56.     UIImage *image = info[UIImagePickerControllerOriginalImage];  
  57.     // 设置imageView  
  58.     _imageView.image = image;  
  59.     // 选择相片完毕,必须手动关闭控制器UIImagePickerController  
  60.     [picker dismissViewControllerAnimated:YES completion:nil];  
  61. }  
  62. // 响应按钮点击,AFN构造multipartFormRequest上传图片到服务器  
  63. - (IBAction)upload {  
  64.     // 1.设置基准路径  
  65.     AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:[NSURL   
  66.                          URLWithString:@"http://169.254.178.47:8080/MJServer"]];  
  67.     // 2.构建NSURLRequest,multipartFormRequestWithMethod  
  68.     NSURLRequest *request = [client multipartFormRequestWithMethod:@"POST"   
  69.                             path:@"upload" parameters:@{  
  70.                             @"username" : @"123",  
  71.                             @"pwd":@"456"}  
  72.         constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {  
  73.         // 上传Default.png  
  74.         [formData appendPartWithFileURL:[[NSBundle mainBundle]  
  75.                             URLForResource:@"Default" withExtension:@"png"]  
  76.                             name:@"file" error:nil];  
  77.         // 上传新获得的图片文件  
  78.         NSData *data = UIImagePNGRepresentation(_imageView.image);  
  79.         [formData appendPartWithFileData:data name:@"file"  
  80.                                 fileName:@"456.png" mimeType:@"image/png"];  
  81.               
  82.         // 上传artifacts.xml  
  83.         [formData appendPartWithFileURL:[[NSBundle mainBundle]   
  84.                         URLForResource:@"artifacts" withExtension:@"xml"]   
  85.                         name:@"file" error:nil];  
  86.           
  87.         // 上传epl-v10.html  
  88.         [formData appendPartWithFileURL:[[NSBundle mainBundle]   
  89.                         URLForResource:@"epl-v10" withExtension:@"html"]   
  90.                         name:@"file" error:nil];  
  91.     }];  
  92.       
  93.     // 3.通过请求构造AFHTTPRequestOperation  
  94.     AFHTTPRequestOperation *operation = [client  
  95.                             HTTPRequestOperationWithRequest:request  
  96.                             success:nil failure:nil];  
  97.     // 4.手动启动AFHTTPRequestOperation  
  98.     [operation start];  
  99. }  
  100. @end  

H:/0917/07_视频播放_PlayViewController.m
[objc] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. //  PlayViewController.m  
  2. //  07-视频播放  
  3. //  Created by apple on 13-9-17.  
  4. /* 
  5.     播放音乐:AVAudioFoundation 
  6.     播放音效:SystemSoundID 
  7.     播放视频:MPMoviePlayerViewController 只能全屏 
  8.     播放视频:MPMoviePlayerController 
  9.              尺寸可以任意大小,继承自NSObject,但成员有view 
  10.              PlayerController状态改变的时候,不是用代理,而是通知 
  11.              当didFinish的时候,收听到了通知,并手动退出全屏 
  12.               
  13.     autoresizingMask 随着屏幕宽高自动伸缩~~~ 
  14.     _player.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | 
  15.                                     UIViewAutoresizingFlexibleHeight; 
  16.                                      
  17.     #pragma mark 要想横屏,必须支持自动旋转 
  18.     - (BOOL)shouldAutorotate 
  19.     { 
  20.         return YES; 
  21.     } 
  22.     #pragma mark 要想横屏,必须只支持横屏方向 
  23.     - (NSUInteger)supportedInterfaceOrientations 
  24.     { 
  25.         return UIInterfaceOrientationMaskLandscape; 
  26.     } 
  27. */  
  28. #import "PlayViewController.h"  
  29. #import <MediaPlayer/MediaPlayer.h>  
  30. /* 
  31.     本控制器,是由上一个控制器,利用trigger segues方法modal(非push)过来的, 
  32.     performSegueWithIdentifier:@"play",play是SB中写死的 
  33.     而且切换过程中,SB中设置了无动画, 
  34.     一进入本控制器,即开始横屏且全屏播放视频 
  35.     一旦didFinish播放完毕,则退出全屏 
  36.     一旦退出全屏,则dismiss本控制器,回显上一个控制器     
  37. */  
  38. @interface PlayViewController ()  
  39. {  
  40.     // 成员:视频播放控制器  
  41.     MPMoviePlayerController *_player;  
  42. }  
  43. @end  
  44. @implementation PlayViewController  
  45. - (void)viewDidLoad  
  46. {  
  47.     [super viewDidLoad];      
  48.     // 从mainBundle中加载视频文件,url  
  49.     NSURL*url = [[NSBundle mainBundle] URLForResource:@"sample_iTunes"   
  50.                                                 withExtension:@"mov"];  
  51.     // 根据url,实例化 视频播放控制器                                              
  52.     _player = [[MPMoviePlayerController alloc] initWithContentURL:url];  
  53.     // 设置 视频播放控制器 为全屏播放  
  54.     _player.view.frame = self.view.bounds;  
  55.     // autoresizingMask 随着屏幕宽高自动伸缩~~~  
  56.     _player.view.autoresizingMask = UIViewAutoresizingFlexibleWidth |  
  57.                                     UIViewAutoresizingFlexibleHeight;  
  58.     [self.view addSubview:_player.view];  
  59.     // 手动播放 视频播放控制器  
  60.     [_player play];  
  61.     // 监听通知  
  62.     // 播放状态改变的通知:播放\暂停  
  63.     [[NSNotificationCenter defaultCenter] addObserver:self   
  64.             selector:@selector(stateChange)  
  65.             name:MPMoviePlayerPlaybackStateDidChangeNotification object:_player];  
  66.     // 播放完毕的通知:目的是退出全屏  
  67.     [[NSNotificationCenter defaultCenter] addObserver:self  
  68.             selector:@selector(didFinish)   
  69.             name:MPMoviePlayerPlaybackDidFinishNotification object:_player];  
  70.     // 截取到某个时间段的图片的通知  
  71.     [[NSNotificationCenter defaultCenter] addObserver:self  
  72.             selector:@selector(captureImage:)   
  73.             name:MPMoviePlayerThumbnailImageRequestDidFinishNotification  
  74.             object:_player];  
  75.     // 当用户退出全屏的通知时,就回到上一个控制器  
  76.     [[NSNotificationCenter defaultCenter] addObserver:self  
  77.             selector:@selector(exitFullScreen)   
  78.             name:MPMoviePlayerDidExitFullscreenNotificationobject:_player];  
  79.     // 截图,精确播放到第3.0秒和第7.0秒时,发送通知,并将截的图作参传递过去   
  80.     // 这儿有个陷阱,必须是小数,单位是秒  
  81.     [_player requestThumbnailImagesAtTimes:@[@3.0@7.0]  
  82.                         timeOption:MPMovieTimeOptionExact];  
  83. }  
  84. #pragma mark 要想横屏,必须支持自动旋转  
  85. - (BOOL)shouldAutorotate  
  86. {  
  87.     return YES;  
  88. }  
  89. #pragma mark 要想横屏,必须只支持横屏方向  
  90. - (NSUInteger)supportedInterfaceOrientations  
  91. {  
  92.     return UIInterfaceOrientationMaskLandscape;  
  93. }  
  94.   
  95. #pragma mark ios 5.0之前的方法  
  96. - (BOOL)shouldAutorotateToInterfaceOrientation:  
  97.                     (UIInterfaceOrientation)toInterfaceOrientation  
  98. {  
  99.     return UIInterfaceOrientationIsLandscape(toInterfaceOrientation);  
  100. }  
  101. // 方法,播放器状态改变的时候,调用  
  102. /* 
  103.  MPMoviePlaybackState Stopped,停止 
  104.  MPMoviePlaybackState Playing, 播放 
  105.  MPMoviePlaybackState Paused, 暂停 
  106.  MPMoviePlaybackState Interrupted, 中断 
  107.  MPMoviePlaybackState SeekingForward, 快进 
  108.  MPMoviePlaybackState SeekingBackward 快退 
  109.  */  
  110. - (void)stateChange  
  111. {  
  112.     switch (_player.playbackState) {  
  113.         case MPMoviePlaybackStatePlaying:  
  114.             NSLog(@"---播放");  
  115.             // 一开始播放,就全屏,本方法如果在view未显示之前调用无效  
  116.             [_player setFullscreen:YES animated:YES];  
  117.             break;  
  118.         case MPMoviePlaybackStatePaused:  
  119.             NSLog(@"---暂停");  
  120.             break;  
  121.         case MPMoviePlaybackStateStopped:  
  122.             NSLog(@"---停止");  
  123.             break;  
  124.         default:  
  125.             break;  
  126.     }  
  127. }  
  128. // 方法,播放器截屏的时候,调用  
  129. - (void)captureImage:(NSNotification *)note  
  130. {  
  131.     UIImage *image = note.userInfo[MPMoviePlayerThumbnailImageKey];  
  132.       
  133.     // NSLog(@"---%@", image);  
  134.     NSString *file = [NSString stringWithFormat:@"/Users/apple/Desktop/%d.jpg", arc4random()];  
  135.     // JPEGRepresentation的第2个参数是压缩比  
  136.     [UIImageJPEGRepresentation(image, 0.5) writeToFile:file atomically:YES];  
  137. }  
  138. // 方法,播放完毕的时候调用,目的是退出全屏  
  139. - (void)didFinish  
  140. {  
  141.     [_player setFullscreen:NO animated:YES];  
  142. }  
  143. // 方法,当用户退出全屏的时候调用,关闭当前控制器,回到上一个控制器  
  144. - (void)exitFullScreen  
  145. {  
  146.     [self dismissViewControllerAnimated:NO completion:nil];  
  147. }  
  148. @end  

H:/0917/07_视频播放_ViewController.m
[objc] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. //  ViewController.m  
  2. //  07-视频播放  
  3. //  Created by apple on 13-9-17.  
  4. //  Copyright (c) 2013年 itcast. All rights reserved.  
  5. #import "ViewController.h"  
  6. @interface ViewController ()  
  7. @end  
  8. @implementation ViewController  
  9. // 响应按钮点击,进入下一个控制器,Identifier:@"play"是在SB连线的时候写的  
  10. - (void)play  
  11. {  
  12.     [self performSegueWithIdentifier:@"play" sender:nil];  
  13. }  
  14. @end 
0 0