iOS网络iOS网络请求

2.1 请求相关及其问题

2015-10-05  本文已影响117人  SoftKnife
People Lack Willpower,Rather Than Strength!

1.简单请求.url中的多值参数问题

2.服务器返回数据的打印问题

3.请求还有哪些类型?

3.1文件下载

3.1.1小文件下载

// 小文件下载

//1.直接使用url下载

NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/images/minion_02.png"];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];

//2.发请求
// 1.url
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/images/minion_02.png"];
// 2.request
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 3.sendrequest
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    UIImage *image = [UIImage imageWithData:data];
    NSLog(@"%@",image);
}];

3.1.2大文件下载

3.1.3大文件断点下载

3.2文件上传

3.2.1复杂的文件上传格式

3.2.2上传文件格式简化

4.其他

4.1压缩与解压

4.2MIMETYPE


| 类型   | 文件拓展名            | MIMEType               | 
| ---- | ---------------- | ---------------------- | 
| 图片| png              | image/png              | 
|  ... | bmp\dib          | image/bmp              | 
| ...  | jpe\jpeg\jpg     | image/jpeg             | 
| ...  | gif               | image/gif              | 
| 多媒体  | mp3              | audio/mpeg             | 
| ...  | mp4\mpg4\m4vmp4v | video/mp4              | 
| 文本   | js               | application/javascript | 
| ...  | pdf              | application/pdf        | 
| ...  | text\txt         | text/plain             | 
| ...  | json             | application/json       | 
| ...  | xml              | text/xml               | 


### 4.3NSURLConnection与NSRunloop的关系
- 测试发送请求是异步or同步, 回调方法在哪个线程执行
  - 1.请求是异步发送;
  - 2.回调方法在主线程中执行.
  
  ``` objective-c
  - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
  {
     // 1.创建一个get请求的url
      NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_02.mp4"];
  
      // 2.request
      NSURLRequest *request = [NSURLRequest requestWithURL:url];
  
      // 3.发送请求
      //    [NSURLConnection connectionWithRequest:request delegate:self];
      [[NSURLConnection alloc] initWithRequest:request delegate:self];
  
      NSLog(@"%s",__func__);
  
    /*有结果可见:
       1.由于还未下载完,就打印-[ViewController touchesBegan:withEvent:],所以是异步发送请求;
       2.代理方法(回调方法)在主线程中执行,系统默认,考虑到我们可能会在这些回调方法中刷新UI,所以默认安排在主线程;
       2015-09-08 16:44:39.259 15-NSURLConnection和NSRunLoop[4493:1058916] -[ViewController touchesBegan:withEvent:]
       2015-09-08 16:44:39.413 15-NSURLConnection和NSRunLoop[4493:1058916] <NSThread: 0x7f8d6b406870>{number = 1, name = main}
     .........
       */
  
  }
  //=====  #pragma mark - NSURLConnectionDataDelegate ========
  - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
  {
      NSLog(@"%@",[NSThread currentThread]);
  
  }
  ......

}
​```

上一篇下一篇

猜你喜欢

热点阅读