IOS中强大的网络通信类库:AFNetworking

ew3y 7年前

AFNetworking提供了非常强大而实用的网络操作API,结合使用NSURL和NSRequest来实现具体的网络操作。

1,Objective-C版本:

以获取推ter的一个接口文件为例

#import <AFNetworking/AFNetworking.h>    NSURL *url = [NSURL URLWithString:@"http://api.推ter.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,要先在工程中建立一个Bridging-Header.h头文件,其中#import <AFNetworking/AFNetworking.h>,

然后在工程的build settings里边寻找bridging,输入指定的OC头文件,即在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!"                }        )    }