我的GitHub
0%

AFnetworking的常见问题

废话不多说,直接上问题:
1.如何拼接请求头?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//申明返回的结果是json类型

manager.responseSerializer = [AFJSONResponseSerializer serializer];

//申明请求的数据是json类型

manager.requestSerializer=[AFJSONRequestSerializer serializer];

// /如果报接受类型不一致请替换一致text/html或别的

[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[manager.requestSerializer setValue:value forHTTPHeaderField:key];
[manager.requestSerializer setValue: value forHTTPHeaderField:key];
[manager.requestSerializer setValue: value forHTTPHeaderField:key];


2.如何返回参数在调用的同一方法中?

block,参数带有block去实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
__block NSString *longitude; // __block,静态变量
[self.manager POST:URL parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) {

NSDictionary *locDictionary = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
longitude = [locDictionary objectForKey:@"lon"]; // 纠正后经度

if (finishBlock)
{
finishBlock(longitude, nil);
}

} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"%@", error);
if (finishBlock)
{
finishBlock(nil, error);
}
}];
我是阿星,阿星的阿,阿星的星!