IOS中強大的網絡通信類庫AFNetworking使用示例

jopen 9年前發布 | 2K 次閱讀 C/C++ Objective-C

AFNetworking提供了非常強大而實用的網絡操作API,結合使用NSURL和NSRequest來實現具體的網絡操作。

1,Objective-C版本:

以獲取twitter的一個接口文件為例

#import <AFNetworking/AFNetworking.h>

NSURL *url = [NSURL URLWithString:@"http://api.twitter.com/1/statuses/public_timeline.json"];

NSURLRequest *request = [NSURLRequest requestWithURL: url];

// 使用AFJSONRequestOperation用于處理JSON格式的response數據。

// 同理還有AFXMLRequestOperation,AFPropertyListRequestOperation,

// AFImageRequestOperation等,都是AFHTTPRequestOperation的子類。

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest: request

    success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {

        NSLog(@"Public Timeline: %@", JSON);

    } failure:nil];

[operation start];

說實話,IOS中的寫法真是繁瑣,不過字面意思確實表達足夠精確。


2,Swift中

若要使用AFNetworking,可將AFNetworking的目錄拖至項目中。在項目的工程中建立一個Bridging-Header.h頭文件,其中#import “AFNetworking/AFNetworking.h”,

然后在工程的build settings里邊尋找bridging,添加指定的bridge文件Bridging-Header.h,即在Swift工程中導入了OC的類庫。

下邊的例子,根據latitude和longitude來獲取天氣信息

fun updateWeatherInfo(latitude: CLLocationDegrees, longitude: CLLocationDegrees) {

    let manager = AFHTTPRequestOperationManager()

    let url = "http://api.openweathermap.org/data/2.5/weather"

    let params = ["lat": latitude, "lon": longitude, "cnt": 0]

    manager.GET(url,

            parameters: params,

            success: { (operation: AFHTTPRequestOperation!,

                          responseObject: AnyObject!) in

                          println("JSON: " + responseObject.description!)

                          self.updateUISuccess(responseObject as NSDictionary!)

            },

            failure: { (operation: AFHTTPRequestOperation!,

                          error: NSError!) in

                          println("Error: " + error.localizedDescription)

                          self.loading.text = "Internet appears down!"

            }

    )

}


 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!