| 注册
请输入搜索内容

热门搜索

Java Linux MySQL PHP JavaScript Hibernate jQuery Nginx
ew3y
9年前发布

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

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!"                }        )    }


 本文由用户 ew3y 自行上传分享,仅供网友学习交流。所有权归原作者,若您的权利被侵害,请联系管理员。
 转载本站原创文章,请注明出处,并保留原始链接、图片水印。
 本站是一个以用户分享为主的开源技术平台,欢迎各类分享!
 本文地址:https://www.open-open.com/lib/view/open1420536453546.html
iOS开发 移动开发 AFNetworking