一、網(wǎng)絡(luò)請求的基礎(chǔ)知識
ios9: 重大改變
(1)
NSURLConnection:ios9之前使用,之后棄用
NSURLSession ios7.0之后出來 ios9只能使用這個類
(2)后臺服務(wù)器傳輸協(xié)議由HTTP改成HTTPS(都是超文本傳輸協(xié)議)
HTTP:Hypertext Transfer Protocol
https:Hyper Text Transfer Protocol over Secure Socket
Layer
區(qū)別: https比http多了 安全套接字層 更安全都是超文本傳輸協(xié)議
(3)常用的請求方法
① get 數(shù)據(jù)寫在URL后面
瀏覽器和服務(wù)器對URl長度有限制,因此在URL后面附帶的參數(shù)是有限制的
② post
默認(rèn)是get
(4) 一個URL加載的請求 NSURLRequest
NSURLRequest子類為NSMutableURLRequest 可以添加請求體 請求頭 請求體就是body數(shù)據(jù) 請求頭是格式
(5)注意在info.plist中添加 否則無法請求數(shù)據(jù)
info.plist -> App Transport Security Settings -> Allow Arbitrary Loads -> YES

二、具體請求示例
-
1、簡單的請求一張圖片并且顯示出來(在這下載demo)
//
// ViewController.m
// RequestDemo
//
// Created by 王龍 on 16/3/27.
// Copyright ? 2016年 Larry(Lawrence). All rights reserved.
//#import "ViewController.h" @interface ViewController ()<NSURLSessionDownloadDelegate> { UIImageView *myView; } @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor greenColor]; /* 下載步驟 1、URL 2、request 3、session 4、下載任務(wù) -> 掛上代理 -> 下載的內(nèi)容在代理方法中得到 5、開啟任務(wù) */ // 1、URL NSURL *url1 = [NSURL URLWithString:@"http://img.pconline.com.cn/images/upload/upc/tx/wallpaper/1206/18/c0/12043463_1339987116999.jpg"]; // 2、request NSURLRequest *requ = [NSURLRequest requestWithURL:url1]; // 3、session對象 NSURLSession *session1 = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]]; // 4、下載任務(wù) NSURLSessionDownloadTask *download = [session1 downloadTaskWithRequest:requ]; // 5、開啟任務(wù) [download resume]; // 初始化圖片視圖來顯示請求下來的圖片 注意需要等待一會才可以請求下來 myView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), CGRectGetHeight([UIScreen mainScreen].bounds))]; myView.backgroundColor = [UIColor cyanColor]; myView.contentMode = UIViewContentModeScaleAspectFit; [self.view addSubview:myView]; } - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{ // NSFileManager 用于文件操作的類 // 創(chuàng)建文件操作的對象 -> 單例 -> defaultManager NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename]; // 移動URL路徑的方法 [[NSFileManager defaultManager] moveItemAtURL:location toURL:[NSURL fileURLWithPath:path] error:nil] ; // 輸出路徑 鼠標(biāo)點(diǎn)擊桌面后 commend+shift+G把這個路徑拷貝過去可以查看下載下來的圖片 NSLog(@"%@",path); myView.image = [UIImage imageWithContentsOfFile:path]; // NSLog(@"%@",location); } @end 2.在這給出具體的一個請求網(wǎng)絡(luò)數(shù)據(jù)的實(shí)例,在這個demo中封裝了請求數(shù)據(jù)的方法,并且以請求天氣預(yù)報數(shù)據(jù)為例,輸入對應(yīng)的城市拼音在控制臺輸出天氣相關(guān)參數(shù)請?jiān)谶@下載具體的demo,封裝好了的請求類,在控制臺查看相關(guān)數(shù)據(jù)。