目錄:
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 manager];
3. //調用get方法
4. [manager GET:@“http://example.com/resources.json”parameters : 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 manager];
2. NSDictionary *parameters = @{@"foo": @"bar"};
3. [manager POST:@"http://example.com/resources.json" parameters:parameters success:^(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 manager];
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 constructingBodyWithBlock:^(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 defaultSessionConfiguration];
2. AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
3.
4. NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"];
5. NSURLRequest *request = [NSURLRequest requestWithURL:URL];
6.
7. NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
8. NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
9. return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
10. } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
11. NSLog(@"File downloaded to: %@", filePath);
12. }];
13. [downloadTask resume];
3、創建一個上傳文件的任務
[objc] view plaincopy
1. NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
2. AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration: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 responseObject, 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?" parameters: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 encoding:NSUTF8StringEncoding];
12. // NSLog(@"%@",stringData);
13.
14. } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
15. NSLog(@"NOT OK");
16. }];