情景:服务器端人员需要 iOS 端发送 int/bool 类型数据, 通过 AFNetworking 进行请求时该如何定义 param 呢?
配置参数的几种格式:
NSDictionary *para = @{
@"param1": @"1",
@"param2": @(2),
@"param3": @(YES),
@"param4": @(true)
};
[NETWORK POST_URL:@"/news" params:para success:^(id result, NSInteger statusCode, NSURLSessionDataTask *task) {
NSLog(@"%@", result);
} failure:^(NSError *error, NSInteger statusCode, NSURLSessionDataTask *task) {
NSLog(@"%@", error.localizedDescription);
}];
- param1 ✅ ->后台接收字符串类型
- param2 ✅->后台接收 int 类型
- param3 ✅->后台接收 bool 类型
- param4 ❌->后台接收 int 类型
AFN 处理方式:
if (parameters) {
if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) {
[mutableRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
}
if (![NSJSONSerialization isValidJSONObject:parameters]) {
if (error) {
NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"The `parameters` argument is not valid JSON.", @"AFNetworking", nil)};
*error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo];
}
return nil;
}
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:self.writingOptions error:error];
if (!jsonData) {
return nil;
}
[mutableRequest setHTTPBody:jsonData];
}
网友评论