我试图从谷歌距离api使用NSURLSession获取数据,但如下所示,当我打印响应和数据时,我得到的结果为NULL.
可能是什么问题?或者是否有任何其他更好的方法来获取 JSON数据.
可能是什么问题?或者是否有任何其他更好的方法来获取 JSON数据.
Nsstring *urlAsstring = [Nsstring stringWithFormat:@"https://maps.googleapis.com/maps/api/distancematrix/json?origins=Vancouver+BC|Seattle&destinations=San+Francisco|Victoria+BC&mode=bicycling&language=fr-FR&key=API-KEY"];
NSURL *url = [NSURL URLWithString:urlAsstring];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithURL:[NSURL URLWithString:urlAsstring]
completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
NSLog(@"RESPONSE: %@",response);
NSLog(@"DATA: %@",data);
}] resume];
解决方法
你应该在你的url字符串上使用stringByAddingPercentEscapesUsingEncoding:这就是你没有得到响应的原因:服务器返回了一个错误.
你应该检查错误;)
我在URL字符串中替换了您的API密钥,如果您复制/粘贴我的代码,请记得自己放置:)
Nsstring *urlAsstring = [Nsstring stringWithFormat:@"https://maps.googleapis.com/maps/api/distancematrix/json?origins=Vancouver+BC|Seattle&destinations=San+Francisco|Victoria+BC&mode=bicycling&language=fr-FR&key=YOUR-API-KEY"];
NSCharacterSet *set = [NSCharacterSet URLQueryAllowedCharacterSet];
Nsstring *encodedUrlAsstring = [urlAsstring stringByAddingPercentEncodingWithAllowedCharacters:set];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithURL:[NSURL URLWithString:encodedUrlAsstring]
completionHandler:^(NSData *data,NSError *error) {
NSLog(@"RESPONSE: %@",response);
NSLog(@"DATA: %@",data);
if (!error) {
// Success
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSError *jsonError;
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
if (jsonError) {
// Error Parsing JSON
} else {
// Success Parsing JSON
// Log NSDictionary response:
NSLog(@"%@",jsonResponse);
}
} else {
//Web server is returning an error
}
} else {
// Fail
NSLog(@"error : %@",error.description);
}
}] resume];