作者:Mitchell
一、NSURLConnection
- iOS7之后不建議使用
- GET請求
- 發送同步請求
// 1.創建一個URL
NSURL *url = [NSURL URLWithString:@"httpAddress"];
// 2.根據URL創建NSURLRequest對象
// 默認情況下NSURLRequest會自動給我們設置好請求頭
// request默認情況下就是GET請求
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 3.利用NSURLConnection對象發送請求
/*
第一個參數: 需要請求的對象
第二個參數: 服務返回給我們的響應頭信息
第三個參數: 錯誤信息
返回值: 服務器返回給我們的響應體
*/
// NSURLResponse *response = nil;
NSHTTPURLResponse *response = nil; // 真實類型
// 注意點: 如果是調用NSURLConnection的同步方法, 會阻塞當前線程
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
- 發送異步請求
// 1.創建一個URL
NSURL *url = [NSURL URLWithString:@"httpAddress"];
// 2.根據URL創建NSURLRequest對象
// 默認情況下NSURLRequest會自動給我們設置好請求頭
// request默認情況下就是GET請求
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 3.利用NSURLConnection對象發送請求
/*
第一個參數: 需要請求的對象
第二個參數: 回調block的隊列, 決定了block在哪個線程中執行
第三個參數: 回調block
*/
// 注意點: 如果是調用NSURLConnection的同步方法, 會阻塞當前線程
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
/*
response: 響應頭
data : 響應體
connectionError : 錯誤信息
*/
// NSLog(@"%@", [NSThread currentThread]);
NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}];
- POST請求:
// 1.創建一個URL
NSURL *url = [NSURL URLWithString:@"http://admin/login"];
// 2.根據URL創建NSURLRequest對象
// NSURLRequest *request = [NSURLRequest requestWithURL:url];
/*
NSMutableURLRequest中保存了請求的地址/請求頭/請求體
*/
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// 2.1設置請求方式
// 注意: POST一定要大寫
request.HTTPMethod = @"POST";
// 2.2設置請求體
// 注意: 如果是給POST請求傳遞參數: 那么不需要寫?號
request.HTTPBody = [@"username=Mitchell&pwd=123456&type=JSON" dataUsingEncoding:NSUTF8StringEncoding];
// 3.利用NSURLConnection對象發送請求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}];
- NSURLConnection 與 NSRunLoop 的關聯使用
- 主要是區分 NSURLConnection 在主線程和子線程發送網絡請求的區別
- 主線程
- 1、 直接發送網絡請求,發送是異步的,但是代理方法是在主線程中執行的:
NSURL*url = [NSURL URLWithString:@"http://mvvideo1.meitudata.com/55d99e5939342913.mp4"];
NSURLRequest*request = [NSURLRequest requestWithURL:url];
//這里分兩種方式發送請求
//2.1 直接發送網絡請求是異步的,但是回調方法是在主線程中執行的
//[[NSURLConnection alloc]initWithRequest:request delegate:self];
* 2、如果按照如下設置,那么回調的代理方法也會運行在子線程中:
NSURL*url = [NSURL URLWithString:@"http://mvvideo1.meitudata.com/55d99e5939342913.mp4"];
NSURLRequest*request = [NSURLRequest requestWithURL:url];
//2.2 設置回調方法也在子線程中運行
NSURLConnection*conn = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:NO];
[conn setDelegateQueue:[[NSOperationQueue alloc] init]];
[conn start];
- 子線程
* `因為 NSURLConnection 是局部變量`,當我們創建的時候其實是會默認`添加到當前的 RunLoop 中`,如果是在主線程添加,主線程的 RunLoop 是默認有的,無須我們創建,`然而如果再子線程中,是默認沒有 RunLoop 和輸入源的,所以需要給子線程手動添加 RunLoop` 。
* 為什么使用 `start` 方法就可以呢?
因為 start
方法如果沒有 RunLoop ,會默認添加一個 RunLoop 到當前的線程中來。
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_async(queue, ^{
NSURL*url = [NSURL URLWithString:@"http://mvvideo1.meitudata.com/55d99e5939342913.mp4"];
NSURLRequest*request = [NSURLRequest requestWithURL:url];
//2.1 這么設置還是可以的
//NSURLConnection*conn = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:NO];
//[conn setDelegateQueue:[[NSOperationQueue alloc] init]];
//[conn start];
//2.2 但是這樣設置就不行了
//[NSURLConnection connectionWithRequest:request delegate:self];
/*問題一:為什么?
NSURLConnection 是臨時變量,當運行的時候被默認添加到當前線程的 RunLoop 中,由于主線程的RunLoop是默認存在的,所以可以運行,這里不行能的原因就是當前線程并沒有 RunLoop,如果想讓其運行,比需要創建RunLoop。
問題二:為什么2.1就可以?
因為start方法:如果沒有一個runloop,它會自動給當前線程添加runLoop,然后將connection加到runLoop中。
If you don’t schedule the connection in a run loop or an operation queue before calling this method, the connection is scheduled in the current run loop in the default mode.
*/
//2.2解決方式
NSRunLoop*loop = [NSRunLoop currentRunLoop];
[NSURLConnection connectionWithRequest:request delegate:self];
[loop run];
});
二、NSURLSession
- 推薦使用
- 簡單使用
- Get
- Get
//注意:如果需要改請求頭 需要使用這種方法
NSURL*url = [NSURL URLWithString:@"httpAddress"];
NSURLRequest*request = [NSURLRequest requestWithURL:url];
//1、創建NSURLSession
NSURLSession*session = [NSURLSession sharedSession];
//2、利用NSURLSession創建Tash
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
/*
data:服務器返回高i的數據
response:響應頭
error:錯誤信息
*/
NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
}];
//3、執行Task
[task resume];
*
NSURL*url = [NSURL URLWithString:@"httpAddress"];
//1、創建NSURLSession
NSURLSession*session = [NSURLSession sharedSession];
//2、利用NSURLSession創建Tash
// 如果是通過url的方法創建Task,方法內部會自動根據URL創建一個request
// 如果是發送Get請求,或者不需要設置請求頭信息,那么建議使用當前方法發送請求
NSURLSessionDataTask*task = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
}];
//3、執行Task
[task resume];
- POST
NSURL*url = [NSURL URLWithString:@"httpAddress"];
NSMutableURLRequest*request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
request.HTTPBody =@"需要發送的信息";
//1、創建NSURLSession
NSURLSession*session = [NSURLSession sharedSession];
//2、利用NSURLSession創建Tash
NSURLSessionDataTask*task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
}];
//3、執行Task
[task resume];
- 斷點下載
#import "ViewController.h"
#import "NSString+Mitchell.h"
@interface ViewController () <NSURLSessionDataDelegate>
@property (weak, nonatomic) IBOutlet UIProgressView *pro;
@property (weak, nonatomic) IBOutlet UIButton *startBtn;
@property (weak, nonatomic) IBOutlet UIButton *cancelBtn;
@property (nonatomic,strong) NSURLSession * session;
@property(nonatomic,assign)CGFloat totalLength;
@property(nonatomic,assign)CGFloat currentLength;
@property(nonatomic,strong)NSURLSessionDataTask*task;
@property(nonatomic,strong)NSOutputStream * stream;
@property(nonatomic,strong)NSString * path;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//初始化操作
//1、初始化文件路徑
self.path = [@"abc.mp4" cacheDir];
//2、初始化當前下載進度
self.currentLength = [self getFileSizeWithPath:self.path];
}
#pragma mark ------------------ delegate ------------------
//注意:NSURLSessionDataTask的代理方法中,默認情況下是不接受服務器返回的數據的,所以didCompleteWithError、didReceiveData默認不會被調用
//如果想接受服務器返回的數據,必須手動告訴系統,我們需要接受數據
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler{
NSLog(@"didReceiveResponse");
self.totalLength = response.expectedContentLength;
//告訴服務器接受,才能調用didCompleteWithError、didReceiveData兩個方法
NSString*path = [@"abc.mp4" cacheDir];
NSLog(@"%@",path);
_stream = [NSOutputStream outputStreamToFileAtPath:path append:YES];
[_stream open];
completionHandler(NSURLSessionResponseAllow);
}
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data{
self.currentLength +=data.length;
self.pro.progress = 1.0*_currentLength/_totalLength;
[_stream write:data.bytes maxLength:data.length];
NSLog(@"didReceiveData");
}
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
NSLog(@"didCompleteWithError");
[_stream close];
_stream = nil;
}
- (NSURLSession *)session{
if (!_session) {
//1、創建NSURLSession
_session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
}
return _session;
}
- (NSURLSessionDataTask *)task{
if (!_task) {
//圖片:http://img1.imgtn.bdimg.com/it/u=298400068,822827541&fm=21&gp=0.jpg%2F2008-09-08%2F200898163242920_2.jpg&bdtype=0&fr=ala&ala=1&alatpl=others&pos=1
//MP4:http://mvvideo1.meitudata.com/55d99e5939342913.mp4
NSURL*url = [NSURL URLWithString:@"http://mvvideo1.meitudata.com/55d99e5939342913.mp4"];
NSMutableURLRequest*request = [NSMutableURLRequest requestWithURL:url];
NSString*range = [NSString stringWithFormat:@"bytes:%zd-",[self getFileSizeWithPath:self.path]];
[request setValue:range forHTTPHeaderField:@"Range"];
//2、利用NSURLSession創建Tash
_task = [self.session dataTaskWithURL:url];
}
return _task;
}
- (NSUInteger)getFileSizeWithPath:(NSString*)path{
NSUInteger currentSize = [[[NSFileManager defaultManager]attributesOfItemAtPath:path error:nil][NSFileSize] integerValue];
return currentSize;
}
#pragma mark ------------------ 開始 ------------------
- (IBAction)start:(id)sender {
//3、執行Task
[self.task resume];
}
#pragma mark ------------------ 暫停 ------------------
- (IBAction)pause:(id)sender {
NSLog(@"暫停");
[self.task suspend];
}
#pragma mark ------------------ 繼續 ------------------
- (IBAction)resume:(id)sender {
NSLog(@"繼續");
[self.task resume];
}
#pragma mark ------------------ 取消 ------------------
- (IBAction)cancel:(id)sender {
}
@end
- 下載進度
#import "ViewController.h"
#import "NSString+Mitchell.h"
@interface ViewController ()<NSURLSessionDownloadDelegate>
@property (weak, nonatomic ) IBOutlet UIProgressView *pro;
@property (weak, nonatomic ) IBOutlet UIButton *startBtn;
@property (weak, nonatomic ) IBOutlet UIButton *cancelBtn;
@property (nonatomic,strong) NSURLSessionDownloadTask * task;
@property (nonatomic,strong) NSData * resumeData;
@property (nonatomic,strong) NSURLSession * session;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
#pragma mark ------------------ didFinishDownloadingToURL ------------------
//下載完成時調用
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location{
NSString*toPath = [@"abc.mp4" cacheDir];
NSURL*toUrl = [NSURL fileURLWithPath:toPath];
NSFileManager *manager = [NSFileManager defaultManager];
[manager moveItemAtURL:location toURL:toUrl error:nil];
NSLog(@"%@",toUrl);
NSLog(@"didFinishDownloadingToURL");
_startBtn.userInteractionEnabled = YES;
}
#pragma mark ------------------ didWriteData ------------------
//接收服務器返回的數據時調用
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
//bytesWritten:每次接收了多少
//totalBytesWritten:本地寫入了多少
//totalBytesExpectedToWrite:一共多少
NSLog(@"%zd,%zd,%zd",bytesWritten,totalBytesWritten,totalBytesExpectedToWrite);
self.pro.progress = 1.0* totalBytesWritten/totalBytesExpectedToWrite;
}
#pragma mark ------------------ didResumeAtOffset ------------------
//恢復下載時候調用(使用resumeData恢復下載的時候才能調用)
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes{
NSLog(@"didResumeAtOffset");
}
//下載完成時調用
//如果下載時候error有值,代表著下載出錯
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
NSLog(@"didCompleteWithError");
_startBtn.userInteractionEnabled = YES;
}
#pragma mark ------------------ 開始 ------------------
- (IBAction)start:(id)sender {
//圖片:http://img1.imgtn.bdimg.com/it/u=298400068,822827541&fm=21&gp=0.jpg%2F2008-09-08%2F200898163242920_2.jpg&bdtype=0&fr=ala&ala=1&alatpl=others&pos=1
//MP4:http://mvvideo1.meitudata.com/55d99e5939342913.mp4
NSURL*url = [NSURL URLWithString:@"http://mvvideo1.meitudata.com/55d99e5939342913.mp4"];
NSURLRequest*request = [NSURLRequest requestWithURL:url];
//1、創建NSURLSession
/*
第一個參數:Session的配置信息
第二個參數:代理
第三個參數:規定了代理方法在哪個線程中執行
*/
_session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
//2、利用NSURLSession創建Task
_task = [self.session downloadTaskWithRequest:request];
//3、執行Task
[_task resume];
_startBtn.userInteractionEnabled = NO;
}
#pragma mark ------------------ 暫停 ------------------
- (IBAction)pause:(id)sender {
NSLog(@"暫停");
[_task suspend];
}
#pragma mark ------------------ 繼續 ------------------
- (IBAction)resume:(id)sender {
NSLog(@"繼續");
// [_task resume];
//恢復信息恢復下載,用獲取到resumeData繼續下載
self.task = [_session downloadTaskWithResumeData:_resumeData];
[self.task resume];
}
#pragma mark ------------------ 取消 ------------------
- (IBAction)cancel:(id)sender {
//取消
//注意點:一旦取消,就不能恢復了
// [_task cancel];
//如果是調用了cancelByProducingResumeData方法,方法內部會回調一個block,在block中會將resumeData傳遞給我們
//resumeData中就保存了當前下載任務的配置信息(下載到什么地方,從什么地方恢復等等)
[self.task cancelByProducingResumeData:^(NSData *resumeData) {
self.resumeData = resumeData;
}];
}
@end
- 上傳
#import "ViewController.h"
// 請求頭的
#define MitchellHeaderBoundary @"----xiaomage"
// 請求體的
#define MitchellBoundary [@"------xiaomage" dataUsingEncoding:NSUTF8StringEncoding]
// 結束符
#define MitchellEndBoundary [@"------xiaomage--" dataUsingEncoding:NSUTF8StringEncoding]
// 將字符串轉換為二進制
#define MitchellEncode(str) [str dataUsingEncoding:NSUTF8StringEncoding]
// 換行
#define MitchellNewLine [@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]
@interface ViewController ()<NSURLSessionTaskDelegate>
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
NSURL*url = [NSURL URLWithString:@""];
NSMutableURLRequest*request = [NSMutableURLRequest requestWithURL:url];
//1、創建Session
NSURLSession*session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
//2、根據Seesion創建Task
/*
//注意:fromFile方法是用于PUT請求上傳文件的
//而我們的服務器只支持POST請求上傳文件
NSURL*fileUrl = [NSURL fileURLWithPath:@""];
NSURLSessionUploadTask*task = [session uploadTaskWithRequest:request fromFile:fileUrl completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
}];
*/
/*請求體
第一個參數:需要請求的地址/請求頭/
第二個參數:需要上傳拼接之后的二進制數據
*/
request.HTTPMethod = @"POST";
// NSURL*fileUrl = [NSURL fileURLWithPath:@""];
// NSData*data =[NSData dataWithContentsOfURL:fileUrl];
// 2.2設置請求體
NSMutableData *data = [NSMutableData data];
// 2.2.1設置文件參數
[data appendData:MitchellBoundary];
[data appendData:MitchellNewLine];
// name : 對應服務端接收的字段類型(服務端參數的名稱)
// filename: 告訴服務端當前的文件的文件名稱(也就是告訴服務器用什么名稱保存當前上傳的文件)
[data appendData:[@"Content-Disposition: form-data; name=\"file\"; filename=\"videos.plist\"" dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:MitchellNewLine];
[data appendData:[@"Content-Type: application/octet-stream" dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:MitchellNewLine];
[data appendData:MitchellNewLine];
//上傳文件的數據
NSURL*fileUrl = [NSURL fileURLWithPath:@""];
NSData*imgData = [NSData dataWithContentsOfURL:fileUrl];
[data appendData:imgData];
[data appendData:MitchellNewLine];
[data appendData:MitchellNewLine];
// 2.2.2設置非文件參數
[data appendData:MitchellBoundary];
[data appendData:MitchellNewLine];
// name : 對應服務端接收的字段類型(服務端參數的名稱)
[data appendData:[@"Content-Disposition: form-data; name=\"username\"" dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:MitchellNewLine];
[data appendData:MitchellNewLine];
[data appendData:[@"Mitchell" dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:MitchellNewLine];
// 2.2.3設置結束符號
[data appendData:MitchellEndBoundary];
//注意點:如果利用NSURLSessionUploadTask上傳文件,那么請求體必須卸載fromData參數中,不能設置在request中
//如果設置在request中會被忽略
//
request.HTTPBody = data;
NSURLSessionUploadTask*task = [session uploadTaskWithRequest:request fromData:data completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
}];
//3、執行Task
[task resume];
}
#pragma mark ------------------ Delegate ------------------
//上傳過程中調用
//bytesSent:當前這一次上傳的數據大小
//totalBytesSent:總共已經上傳的數據大小
//totalBytesExpectedToSend:需要上傳文件的大小
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend{
NSLog(@"%f",1.0*totalBytesSent/totalBytesExpectedToSend);
}
//請求完畢時調用
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
//用block方式 創建是不會調用這個方法
}
@end