【发布时间】:2019-01-24 02:54:51
【问题描述】:
在我的代码中,我想将 NSData 转换为 NSDictionary 但它返回 nil 我不知道我犯了什么错误,我使用 NSJSONSerialization 将数据转换为字典,从服务器响应接收到 NSData。
在这里我展示了我正在尝试的完整代码。
-(void)SendPushNotification:(NSString*)getUrl :(NSMutableDictionary *)getData withCompletionBlock:(void(^)(NSDictionary *))completionBlock
{
NSError *error;
NSLog(@"dict val: %@",getData);
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:getData options:NSJSONWritingPrettyPrinted error:&error];// Pass 0 if you don't care about the readability of the generated string
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSData *postData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLengthas = [NSString stringWithFormat:@"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:getUrl]
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:100.0];
NSString *chkRegDevice= [[NSUserDefaults standardUserDefaults] stringForKey:@"bearer"];
NSString *strfds=[NSString stringWithFormat:@"bearer %@",chkRegDevice];
[request setHTTPMethod:@"POST"];
[request setValue:postLengthas forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:strfds forHTTPHeaderField:@"Authorization"];
[request setHTTPBody:postData];
NSURLSessionConfiguration *configg=[NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession*sessionn=[NSURLSession sessionWithConfiguration:configg delegate:nil delegateQueue:[NSOperationQueue mainQueue]];
NSURLSessionDataTask *taskk=[sessionn dataTaskWithRequest:request completionHandler:^(NSData *data,NSURLResponse *responce,NSError *error){
if(error)
{
NSLog(@"%@", [error localizedDescription]);
completionBlock(nil);
}else{
NSError *jsonError;
NSString *clientDetail = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(@"clientDetail: %@", clientDetail);
NSData *objectDataaaaa = [clientDetail dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectDataaaaa options:NSJSONReadingMutableContainers error:&jsonError];
NSLog(@"json %@",json);
if (![clientDetail isEqualToString:@"Object reference not set to an instance of an object."]) {
if (completionBlock) {
completionBlock(json);
}
}
else
{
completionBlock(nil);
}
}
}];
[taskk resume];
}
下面是我将 NSData 转换为 NSString 的响应。
"{\"multicast_id\":8856529321585625357,\"success\":1,\"failure\":0,\"canonical_ids\":0,\"results\":[{\"message_id\" :\"0:1534479035021563%1dbdaa031dbdaa03\"}]}"
【问题讨论】:
-
您的代码中从服务器响应接收到的 NSData 是什么?你能告诉我完整的代码吗?我想知道您使用哪种方法进行 HTTP 请求。
-
我添加了完整代码@VinuJacob
-
好的,在你的 else 条件下试试这个代码。 NSError *e = nil; NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:数据选项:NSJSONReadingMutableContainers 错误:&e]; NSLog(@"响应字典%@",JSON);
-
它也返回 (null).@VinuJacob
-
你在 PostMan 中检查过这个请求吗
标签: ios objective-c nsjsonserialization