AFNetworking使用总结

1 将AFNetWorking文件夹导入项目

2 添加类库 Security.framework、MobileCoreServices.framework、SystemConfiguration.framework

3 在使用的地方 #import "AFNetworking.h"

4.解决编译警告:

<span style="font-size:14px;"><em>Prefix.pch文件中加入
#import <SystemConfiguration/SystemConfiguration.h>
#import <MobileCoreServices/MobileCoreServices.h></em></span>


5.JSON数据解析


(1)根据基本的URL构造出完整的一个URL, 让后通过这个完整的URL获得一个NSURL对象,然后根据这个url获得一个NSURLRequest。

(2)AFNJSONRequestOperation是一个完整的类,整合了送网络中获取数据并对JSON进行解析。

(3)当请求成功,则运行成功块,在本例子中将一个JSON变量转换为一个字典,并将其存在字典中。

(4)如果失败,则运行失败块,比如网络不可用

<pre name="code" class="objc"><span style="font-size:14px;">static NSString *const BaseURLString = @"http://www.raywenderlich.com/downloads/weather_sample";
/*1*/
NSString *weatherUrl = [NSString stringWithFormat:@"%@weather.php?format=json", BaseURLString];
NSURL *url = [NSURL URLWithString:weatherUrl];
NSURLRequest *request = [NSURLRequest requestWithURL:url];                                          

/*2.3.4*/
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:requestsuccess:^(NSURLRequest * request, NSHTTPURLResponse *response, id JSON) {
NSDictonary *dicWeather = (NSDictonary *)JSON; NSLog(@"result:%@", dicWeather); } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *rror, id JSON) { UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error RetrievingWether" message:[NSString stringWithFormat :@"%@", error] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alertView show]; }]; [operation start];</span>


 

6.AFNetworking异步加载图片

<span style="font-size:14px;">// 1
#imptort "UIImageView+AFNetworking.h"
// 2
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(40, 80, 40, 40)];
__weak UIImageView *_imageView;
[imageView setImageWithURLRequest:[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.worldweatheronline.com/images/wsymbols01_png_64/wstmbol_0001_sunny.png"]] placeholderImage:[UIImage imageNamed:@"placeholder.png"] success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
_imageView.image;
[_imageView setNeedsDisplay];
} failure:^(NSURLRequest *request, NSHTTPURLResponse Response, NSError *error) {

}];
[self.view addSubview:imageView];
</span>

7.GET和POST请求


(1)构建一个baseURL,以及一个参数字典,并将这两个变脸传给AFHTTPClient。

(2)将AFJSONRequestOpreation注册为HTTP的操作,这样就可以和之前示例一样,获得解析好的JSON数据

(3)做一个GET请求,这个请求有一对block:success和failure。

(4)POST请求和GET一样


<span style="font-size:14px;">AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
[client registerHTTPOperationClass:[AFJSONRequestOperation class]];
[client setDefeultHeader:@"Accept" value:@"application/json"];
[client postPath:@"weather.php" parameters:parameters success:^(AFNHTTPRequestOperation *operation, id responseObject) {
self.weather = responseObject;
self.title = @"HTTPPOST";
[self.tableView reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather" message:[NSString stringWithFormat:@"%@", error] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[av show];
}];
[client getPath@"weather.php" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
self.weather = responseObject;
self.title = @"HTTP GET";
[self.tableView reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather" message:[NSString stringWithFormat:@"%@", error] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[av show];
}];</span>


8.状态栏设置

在Appdelegate里面的- (BOOL)application:(UIApplication *)application  didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 方法中添加

[AFNetworkActivityIndicatorManager shareManager] setEnabled:YES];  // 用来给用户做出网络访问提示。


9.请求超时设置


(1)timeout和参数都是在NSURLRequest/NSMutableURLRequest设置的

NSMutableURLRequest Request = [client requestWithMethod:@"GET" path:@"/" parameters:nil]; // 这里的parameters:参数就是你的第二个问题如何设置参数
[request setTimeoutInterVal:120];
AFHTTPRequestOperation operation = [client HTTPRequestOperationWithRequest:request success:^{/*...*/} failure:^{/*...*/}];
[client enqueueHTTPRequestOperation:operation];


(2)如果你是继承了AFHTTPClient 就需要override一个方法requestWithMethod

- (NSMutableURLRequest *)requestWithMethod:(NSString *)method path:(NSString *)path parameters:(NSDictionary *)parameters {
NSMutableURLRequest *request = [super requestWithMethod:method path:path parameters:parameters];
[request setTimeoutInterval:15];
return request;
}


(3)这个时候参数设置是调用

[self postPath:@"" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
if (success) {
succes((AFJSONRequestOperation *)operation, responseObject);
}
} failure:^(AFJSONRequestOperation *operation, NSError *error) {
if (failure) {
failure((SFJSONRequestOperation *)operation, error);
}

}];




使用AFNetworking下载文件时,有几种常见的方式。第一种方式是使用AFHTTPRequestOperation进行文件下载,需要传入文件的下载地址URL、自定义的文件名fileName以及下载到的文件路径d_path。 另一种方式是使用AFHTTPSessionManager结合NSURLSessionDownloadTask进行文件下载。同样需要传入文件的下载地址URL和下载到的文件路径d_path。 此外,还可以使用AFNetworking来实现文件的断点下载功能。通过对AFNetworking3.0版本的学习,你可以了解到如何使用AFNetworking来实现文件断点下载,并且可以获取一些有价值的参考信息。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [AFNetworking从指定网址下载文件的两种方式总结](https://blog.csdn.net/u014063717/article/details/52232858)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [iOS利用AFNetworking3.0——实现文件断点下载](https://download.csdn.net/download/weixin_38607784/12786948)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值