目錄:
1
、爲什麼要用
AFNetworking
2
、
AFNetworking
的用法
一、爲什麼要用
AFNetworking
在
ios
開發中,一般情況下,簡單的向某個
web
站點簡單的頁面提交請求並獲取服務器的
響應,用
xcode
自帶的
NSURLConnection
是能勝任的。但是,在絕大部分下我們所需要
訪問的
web
頁面則是屬於那種受到權限保護的頁面,
並不是有一個簡單的
URL
可以訪問的。
這就涉及到了
Session
和
Cookie
的處理了,在此時使用
NSURLConnection
也是能夠達到
要求的,只是其中處理起來的複雜度和難度就提升了。
爲了更好的處理向
Web
站點的請求,包括處理
Session
,
Cookie
等細節問題,使用
AFNetworking
則是更好的選擇,他可以用於發送
HTTP
請求,接收
HTTP
的響應,但是不
會緩存服務器的響應,不能執行
HTML
頁面中的
JAvascript
代碼
,
同時,
AFNetworking
還
內置支持
JSON
,
plist
文件和
XML
文件的解析,使用比較方便。
擴展:
1
、
Session
:中文有譯作時域的,就是隻某個客戶端在訪問服務器起到停止訪問這一段的時間間隔
被稱爲時域。
2
、
Cookie
:由服務器發送給客服端,把
Cookie
的
key
:
value
值儲存在本地文件夾下,當下次請求的
時候能夠直接發送
Cookie
獲得權限驗證
二、
AFNetworking
的用法
1
、提交
GET
請求和提交
POST
請求
AFNetworking
是第三方的框架,所以需要開發者自行下載,安裝。並在
AFNetworking.h
文件導入
#import“AFHTTPRequestOpeartionManager.h ”
,把
AFNetworking.h
頭文件放入
prefix
文件中。
a
、創建
AFHTTPRequestOpeartionManger
對象
b
、根據服務器內容的不同,爲
AFHTTPRequestOpeartionManger
對象指定不同的解析器,該對象默認的
解析器是
JSON
和
Plist
文件解析器。如果服務器的數據是
XML
格式則需要手動的更改解析器
c
、發送
GET
請求:
用
Manager
對象調用
GET
:
parameters
:
success
:
failure
:方法即可,
success
代碼塊和
failue
代碼塊在網絡請求成功
/
失敗過後調用。
d
、
success
:參數指定了代碼塊中處理服務器響應成功的正確數據,
failue
:參數指定了代碼塊中處理服務
器響應失敗的錯誤數據、
AFHTTPRquestOperationManager
包含了常見的
HTTP
訪問
web
站點的模式,有創建請求,連續的響應,網絡類型監視以及安全
。
“GET”
:
[objc]
view plaincopy
1.
<span style=
"font-size:12px;"
>
//
創建
AFHTTPRequestOperationManager
對象
2.
AFHTTPRequestOperationManager
*manager = [AFHTTPRequestOperationManger
m
anager
];
3.
//
調用
get
方法
4.
[manager
GET
:@“http:
//example.com/resources.json”pa
rameters : parameters
5.
//
加載成功的代碼塊,可以接收數據
6.
success:^(
AFHTTPRequestOperation
*operation,
id
responseobject)]{
7.
NSLog(@“json“:%@”,responseObject);
8.
}failure:^(
AFHTTPRequestOperation
*operation,
NSError
*error){
9.
NSLog(@“Error:%@”,error);
10.
}];</span>
”POST“:
URL-Form-Encoded Request
URL
編碼請求類型
[objc]
view plaincopy
1.
AFHTTPRequestOperationManager
*manager = [AFHTTPRequestOperationManager
mana
ger
];
2.
NSDictionary
*parameters = @{
@"foo"
:
@"bar"
};
3.
[manager
POST
:
@"http://example.com/resources.json"
parameters
:parameters
suc
cess
:^(
AFHTTPRequestOperation
*operation,
id
responseObject) {
4.
NSLog(
@"JSON: %@"
, responseObject);
5.
}
failure
:^(
AFHTTPRequestOperation
*operation,
NSError
*error) {
6.
NSLog(
@"Error: %@"
, error);
7.
}];
"POST"
多個請求
[objc]
view plaincopy
1.
AFHTTPRequestOperationManager
*manager = [AFHTTPRequestOperationManager
mana
ger
];
2.
NSDictionary
*parameters = @{
@"foo"
:
@"bar"
};
3.
NSURL
*filePath = [NSURL
fileURLWithPath
:
@"file://path/to/image.png"
];
4.
[manager
POST
:
@"http://example.com/resources.json"
parameters
:parameters
con
structingBodyWithBlock
:^(
id
<AFMultipartFormData> formData) {
5.
[formData
appendPartWithFileURL
:filePath
name
:
@"image"
error
:nil
];
6.
}
success
:^(
AFHTTPRequestOperation
*operation,
id
responseObject) {
7.
NSLog(
@"Success: %@"
, responseObject);
8.
}
failure
:^(
AFHTTPRequestOperation
*operation,
NSError
*error) {
9.
NSLog(
@"Error: %@"
, error);
10.
}];
2
、創建一個下載文件的任務
AFURLSessionManager
創建並完善了一個
NSURLSession
的對象基於遵從
NSURLSessionDelegate
與
NSURLSessionDataDelegate
協議
NSURLSessionConfigration
對象。
[objc]
view plaincopy
1.
NSURLSessionConfiguration
*configuration = [NSURLSessionConfiguration
defaul
tSessionConfiguration
];
2.
AFURLSessionManager
*manager = [[AFURLSessionManager
alloc
]
initWithSessionC
onfiguration
:configuration];
3.
4.
NSURL
*URL = [NSURL
URLWithString
:
@"http://example.com/download.zip"
];
5.
NSURLRequest
*request = [NSURLRequest
requestWithURL
:URL];
6.
7.
NSURLSessionDownloadTask
*downloadTask = [manager
downloadTaskWithRequest
:re
quest
progress
:nil
destination
:^
NSURL
*(
NSURL
*targetPath,
NSURLResponse
*response)
{
8.
NSURL
*documentsDirectoryURL = [[NSFileManager
defaultManager
]
URLForDir
ectory
:NSDocumentDirectory
inDomain
:NSUserDomainMask
appropriateForURL
:nil
create
:
N
O
error
:nil
];
9.
return
[documentsDirectoryURL
URLByAppendingPathComponent
:[response
sugg
estedFilename
]];
10.
}
completionHandler
:^(
NSURLResponse
*response,
NSURL
*filePath,
NSError
*err
or) {
11.
NSLog(
@"File downloaded to: %@"
, filePath);
12.
}];
13.
[downloadTask
resume
];
3
、創建一個上傳文件的任務
[objc]
view plaincopy
1.
NSURLSessionConfiguration
*configuration = [NSURLSessionConfiguration
defaul
tSessionConfiguration
];
2.
AFURLSessionManager
*manager = [[AFURLSessionManager
alloc
]
initWithSessionC
onfiguration
:configuration];
3.
4.
NSURL
*URL = [NSURL
URLWithString
:
@"http://example.com/upload"
];
5.
NSURLRequest
*request = [NSURLRequest
requestWithURL
:URL];
6.
7.
NSURL
*filePath = [NSURL
fileURLWithPath
:
@"file://path/to/image.png"
];
8.
NSURLSessionUploadTask
*uploadTask = [manager
uploadTaskWithRequest
:request
fromFile
:filePath
progress
:nil
completionHandler
:^(
NSURLResponse
*response,
id
resp
onseObject,
NSError
*error) {
9.
if
(error) {
10.
NSLog(
@"Error: %@"
, error);
11.
}
else
{
12.
NSLog(
@"Success: %@ %@"
, response, responseObject);
13.
}
14.
}];
15.
[uploadTask
resume
];
4
、處理
JSON
或
Plist
響應
IOS
應用在處理
JSON
和
Plist
響應的時候可以十分輕便將其轉換成
NSDictionary
對象或者
NSArray
對像,
AFHTTPRequestOpeartionManager
默認就可以處理
JSON
或
Plist
響應,也就是說當我們
response.MIMEType
爲
appication/json
、
text/json,AFHTTPRequestOpeartionManager
默認就可以處理,無需再次指定服務
器響應解析器。
[objc]
view plaincopy
1.
2.
AFHTTPRequestOperationManager
*manager = [AFHTTPRequestOperationManager
manager
];
3.
// manager.responseSerializer = [AFHTTPResponseSerializer serializer];
4.
NSDictionary
*parameter = @{
@"location"
:
@"
長沙
"
,
@"output"
:
@"json"
,
@"ak"
:
@"jlflVx1VTUahj05Q7GfB7PCf"
};
5.
[manager
GET
:
@"http://api.map.baidu.com/telematics/v3/weather?"
paramete
rs
:parameter
success
:^(
AFHTTPRequestOperation
*operation,
id
responseObject) {
6.
NSLog(
@"OK"
);
7.
dic = responseObject;
8.
NSArray
*keys = [dic
allKeys
];
9.
NSLog(
@"%@"
,keys);
10.
// _datas = responseObject;
11.
// NSString *stringData = [[NSString alloc]initWithData:_datas encodi
ng:NSUTF8StringEncoding];
12.
// NSLog(@"%@",stringData);
13.
14.
}
failure
:^(
AFHTTPRequestOperation
*operation,
NSError
*error) {
15.
NSLog(
@"NOT OK"
);
16.
}];