我正在使用
AFNetworking
通过以下代码从服务器获取 API 响应:
void (^AuthLoginCompleteBlock)(BOOL success, NSString *message, NSDictionary *response, NSError *error);
-(void)login:(NSString *)user password:(NSString *)password deviceID:(NSString *)deviceID callback:(authRequestCompleteBlock)callback{
AuthLoginCompleteBlock = callback;
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:user,@"data[User][username]]",password,@"data[User][password]]",deviceID,@"data[User][device_id]]", nil];
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
[manager POST:[NSString stringWithFormat:@"%@/%@",SERVER_URL,LOGIN] parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSString *str = [NSString stringWithFormat:@"%@",responseObject];
AuthLoginCompleteBlock(YES,str,nil,nil);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
AuthLoginCompleteBlock(NO,error.description,nil,nil);
}];
NSLog(@"param = %@",parameters);
}
现在 URL 工作正常,一切看起来都很好,但问题是响应是通过我在
message
块中创建的 AuthLoginCompleteBlock
字符串来的,并且 NSDictionary
响应即将到来 NULL
,看起来像这样(消息字符串)
{
message = "Please enter valid email related to your account.";
status = failed;
}
尝试像这样获取时
NSData *jsonData = [message dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
id json = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&error];
if(!error) {
NSLog(@"hello = %@", json);
}
else{
NSLog(@"errr = %@",error.description);
}
出现以下错误
错误域=NSCocoaErrorDomain代码=3840“字符6周围的对象中的值没有字符串键。”
UserInfo={NSDebugDescription=No
字符 6 周围对象中值的字符串键。这意味着来自服务器的 JSON 格式不正确?但在邮递员中,响应如下并且非常好:
{
"status": "failed",
"message": "Please enter valid email related to your account."
}
如果我遗漏了什么请评论。
问题是我已经有了一本字典,所以我不需要解析它。 bug 就是这两行。
NSString *str = [NSString stringWithFormat:@"%@",responseObject];
AuthLoginCompleteBlock(YES,str,nil,nil);
我正在将字符串发送到我的块,它已经是一本字典。
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
NSDictionary *parameters = @{
@"user": @"login",
@"password": txtFieldPassword.text,
@"device": @"ios",
@"deviceToken": strToken,
};
NSLog(@"parameters is ====%@",parameters);
manager.responseSerializer = [AFJSONResponseSerializer
serializerWithReadingOptions:NSJSONReadingAllowFragments];
[manager POST:@"yourUrl" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject)
{
NSLog(@"success!%@",responseObject);
[self successfullLogin:responseObject];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
{
NSLog(@"error: %@", error);
}];