iOS網路開發之AFNetworking

來源:互聯網
上載者:User

標籤:line   常用   operation   afn   cti   ext   rest   dict   ram   

概述

AFNetworking是一個非常受歡迎的輕量級的iOS、Mac OS X網路通訊類庫。它建立在NSURLConnection、NSOperation以及其技術的基礎上,有著精心設計的模組結構和功能豐富的API,讓很多網路通訊功能的實現變得十分簡單。

AFNetworking支援HTTP請求和基於REST的網路服務(包括GET、POST、 PUT以及DELETE等)。支援ARC。AFNetworking項目中還包含一些列單元測試。

要求iOS 5.0及以上版本,或者Mac OS 10.7及以上版本。

源碼地址:https://github.com/AFNetworking/AFNetworking

 

實踐使用

在源碼裡,已經介紹得很清楚,下面,為大家貼出部分常用的。

Get方法請求

無參數方式:

  AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; [manager GET: @"http://example.com/resources.json"  parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {      NSLog( @"JSON: %@" , responseObject); } failure:^(AFHTTPRequestOperation *operation, NSError *error) {      NSLog( @"Error: %@" , error); }];

 

 有參數方式,其實和無參一樣:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];  NSMutableDictionary  *params = [ NSMutableDictionary  dictionary]; params[@ "param1" ] = @ "1" ; params[@ "param2" ] = @ "2" ;  [manager GET:@ "http://example.com/resources.json"  parameters:params success:^(AFHTTPRequestOperation *operation,  id  responseObject) {      NSLog (@ "JSON: %@" , responseObject); } failure:^(AFHTTPRequestOperation *operation,  NSError  *error) {      NSLog (@ "Error: %@" , error); }];

 Post請求方式:

 

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

NSDictionary  *parameters = @{@ "foo" : @ "bar" }; [manager POST:@ "http://example.com/resources.json"  parameters:parameters success:^(AFHTTPRequestOperation *operation,  id  responseObject) {      NSLog (@ "JSON: %@" , responseObject); } failure:^(AFHTTPRequestOperation *operation,  NSError  *error) {      NSLog (@ "Error: %@" , error); }];

 

另外注意:

我們在請求網路的時候,經常會看到返回資料時,有頭部資訊,如:

Content-Type: application/json

AFNetworking 預設接受的資料類型是(在AFJSONResponseSerializer下):

self .acceptableContentTypes = [ NSSet  setWithObjects:@ "application/json" , @ "text/json" , @ "text/javascript" nil ];

 如果返回的數類是text/plain 則會報錯。

直接加上該類型即可:

self .acceptableContentTypes = [ NSSet  setWithObjects:@ "text/plain" , @ "application/json" , @ "text/json" , @ "text/javascript" nil ];

iOS網路開發之AFNetworking

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.