iOS NSURLSession網路請求(get/post/下載)
阿新 • • 發佈:2019-02-04
NSURLConnection在iOS 9.0以後就廢棄了
DEPRECATED deprecated廢棄的意思
NSURLSession 已經代替了NSURLConnection 功能上差不多.NSURLSession使用起來更方便,支援下載和上傳檔案,斷點續傳等使用起來很方便
蘋果將每次請求都定義為一個任務
NSURLSessionDataTask 是請求普通網路資料的任務類
NSURLSessionUploadTask 上傳任務類(需要和伺服器配合使用)
NSURLSessionDownloadTask 下載任務類
我使用storyBoard拖了3個按鈕,一個imageView,如圖:
關聯控制元件
@interface ViewController : UIViewController
- (IBAction)getBtn:(UIButton *)sender; //get請求
- (IBAction)postBtn:(UIButton *)sender; //post請求
- (IBAction)downImage:(UIButton *)sender; //下載圖片
@property (strong, nonatomic) IBOutlet UIImageView *myImageView; //imageView
@end
宣告屬性
//下載需要籤協議
@interface ViewController ()<NSURLSessionDownloadDelegate>
@property (nonatomic, strong)NSURLSessionDataTask *tast;
@property (nonatomic, strong)NSURLSessionDataTask *posttast;
@property (nonatomic, strong)NSURLSessionDownloadTask *downTast;
@end
get請求
- (IBAction)getBtn:(UIButton *)sender {
//url字串地址
NSString *urlStr = @"http://api.map.baidu.com/place/v2/search?query=銀行®ion=大連&output=json&ak=6E823f587c95f0148c19993539b99295";
//中文編碼
NSString *strEncode = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//廢棄了
//轉碼--->中文,(由於不能轉特殊字元)
// NSString *urlEncode2 = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//生成系統能夠識別的NSURL物件
NSURL *url = [NSURL URLWithString:strEncode];
//建立請求物件
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//建立網路連線物件
NSURLSession *session = [NSURLSession sharedSession];
//建立請求普通資料網路任務tast
self.tast = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//json解析data資料
id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"result == %@", result);
}];
//開始請求任務
[self.tast resume];
}
post請求
- (IBAction)postBtn:(UIButton *)sender {
//post地址
NSString *urlStr = @"http://api.hoto.cn/index.php?appid=4&appkey=573bbd2fbd1a6bac082ff4727d952ba3&appsign=cee6710ae48a3945b398702d8702510a&channel=appstore&deviceid=0f607264fc6318a92b9e13c65db7cd3c%7C552EE383-0FAD-4555-9979-AC38A01C5D6D%7C9C579DCC-7C8F-4E53-AEB6-54527C473309&format=json&loguid=&method=Recipe.getFindRecipe&nonce=1443856978&sessionid=1443856790&signmethod=md5×tamp=1443856978&uuid=02288be08f4b871a69565746255b0de9&v=2&vc=40&vn=v5.1.0";
NSString *strEncode = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSURL *url = [NSURL URLWithString:strEncode];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//設定請求物件的請求方式為post,預設是get請求
[request setHTTPMethod:@"POST"];
NSString *bodyStr = @"cacheKey=Recipe.getFindRecipe&sign=&uid=&uuid=02288be08f4b871a69565746255b0de9";
//將body體字串轉成data資料
NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
//設定為請求的body體
[request setHTTPBody:bodyData];
//建立一個專門配置session的類,是系統對session物件的標準配置
NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
//另一種初始化方法
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig];
self.posttast = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"post result = %@", result);
}];
[self.posttast resume];
}
下載圖片
- (IBAction)downImage:(UIButton *)sender {
NSString *urlStr = @"http://avatar0.hoto.cn/36/76/3962422_185.jpg?v=11";
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSURLSessionConfiguration *sessionCon = [NSURLSessionConfiguration defaultSessionConfiguration];
//引數3:建立一個主執行緒列隊
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionCon delegate:self delegateQueue:[NSOperationQueue mainQueue]];
// NSURLSessionDataDelegate 協議名
//建立下載任務
self.downTast = [session downloadTaskWithRequest:request];
//執行下載任務
[self.downTast resume];
}
//下載完成時呼叫
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
NSLog(@"下載存放的臨時路徑 = %@", location.path);
//獲取app本地快取路徑
NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString*imagePath = [filePath stringByAppendingPathComponent:@"image.png"];
//建立檔案管理器
NSFileManager *fileManager = [NSFileManager defaultManager];
// [NSFileManager defaultManager]是系統單例
//將下載檔案移動到caches檔案下
[fileManager moveItemAtPath:location.path toPath:imagePath error:nil];
NSLog(@"filePath = %@", filePath);
//將下載的圖片顯示到手機上
self.myImageView.image = [UIImage imageWithContentsOfFile:imagePath];
}
下載視訊也是可以的,我直接把下載圖片按鈕的點選事件,改成了下載視訊,並又拖了進度條和2個按鈕,如圖:
關聯控制元件
@property (retain, nonatomic) IBOutlet UIProgressView *progress;
- (IBAction)stopBtn:(UIButton *)sender; //暫停按鈕
- (IBAction)resume:(UIButton *)sender; //繼續按鈕
- (IBAction)downImage:(UIButton *)sender {
NSString *urlStr = @"http://hc25.aipai.com/user/656/20448656/6167672/card/25033081/card.mp4?l=a";
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSURLSessionConfiguration *sessionCon = [NSURLSessionConfiguration defaultSessionConfiguration];
//引數3:建立一個主執行緒列隊
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionCon delegate:self delegateQueue:[NSOperationQueue mainQueue]];
// NSURLSessionDataDelegate 協議名
//建立下載任務
self.downTast = [session downloadTaskWithRequest:request];
//執行下載任務
[self.downTast resume];
}
//下載完成時呼叫
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
NSLog(@"下載存放的臨時路徑 = %@", location.path);
//獲取app本地快取路徑
NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString*imagePath = [filePath stringByAppendingPathComponent:@"image.mp4"];
//建立檔案管理器
NSFileManager *fileManager = [NSFileManager defaultManager];
// [NSFileManager defaultManager]是系統單例
//將下載檔案移動到caches檔案下
[fileManager moveItemAtPath:location.path toPath:imagePath error:nil];
//進到資料夾裡就能看見下載的視訊了
NSLog(@"filePath = %@", filePath);
}
//每下載完一部分就會觸發該方法
//引數1:bytesWritten:下載速度
//引數2:totalBytesWritten:已經下載多少
//引數3:totalBytesExpectedToWrite:檔案總大小
- (void)URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
NSLog(@"速度:%lldkb/s 已經下載:%lldkb 檔案總大小:%lldkb", bytesWritten/1024, totalBytesWritten/1024, totalBytesExpectedToWrite/1024);
//下載的視訊與進度條關聯
double Progress = (double)totalBytesWritten / totalBytesExpectedToWrite;
self.progress.progress = Progress;
}
- (IBAction)stopBtn:(UIButton *)sender {
//暫停下載
[self.downTast suspend];
}
- (IBAction)resume:(UIButton *)sender {
//繼續下載
[self.downTast resume];
}