我试图从谷歌距离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];