AFNetworking 是我们常用的轻量级网络请求,文章的前提是你已经对 AFNetworking 有了基本的掌握。
不太了解的,请链接 iOS 使用AFNetworking。
一 : 唠唠叨叨。
AFNetworking 是建立在 NSURLConnection 和 NSOperation 等类库的基础之上的,取消的网络的请求的操作也就变得很简单。
但 AFNetworking 又没有直接的给出我们取消的方式,这就需要我们添加。
二 :该说实现了 。
如上所言,我们要取消网络请求,无非有两种思想 --
1 - 拿到 NSOperation 进行取消 ;
2 - 通过 AFHTTPClient 集成方法取消;
我们通过继承 AFHTTPClient 并写成单例的网络请求 , AFHTTPClient 简单的就能拿到 -
那 operation 该怎么处理呢 --
三 : 寻找 operaion
我们可以通过外部直接用 operation 请求 --
AFHTTPClient * client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://m.weather.com.cn/data/101110101.html"]];
AFHTTPRequestOperation * operation = [client HTTPRequestOperationWith Request:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
这样就能拿到 operation 进行其他的操作 ---
但是,我们真正的开发中,并不真正这样操作,因为并没有添加到 队列中对 operation 进行管理 ,而且 这样的请求 AFNetworking 并不推荐 --
开发中,我们通过通过继承 AFHTTPClient , 做一些操作 -- 并 使用 - (void)getPath:(NSString *)path
的封装 ---
好 -- 我们看一下 这个方法的实现 ----
- (void)getPath:(NSString *)path
{
NSURLRequest *request = [self requestWithMethod:@"GET" path:path parameters:parameters];
}
我们看到这个方法里是有 operation 的,我们为何不直接返回,拿到这个 operation 呢 ?
写个类似的方法 ---
- (AFHTTPRequestOperation *)getServer:(NSString *)path
{
NSURLRequest *request = [self requestWithMethod:@"GET" path:path parameters:parameters];
}
这样,外部我们就能直接拿到这个 operation 了 --------
这样,外部调用,就成了 ---
AFURLConnectionOperation * operation = [[ZFHTTPClient shared] getFromServer:@"sales"
四 : 是时候取消一个网络请求了 ---
这部分大家看注释哈 ,写的很清楚 --
--------- 确定还要看 ? ---------
没错,万恶的博主并没有留 demo 链接 ---
赶快关注他,给他所要 demo 吧 --- 赶快关注,要demo