在下面的代码中运行,所以我从url获得响应,但是当我尝试获取encodedPoints
时,它会给我一个空值。我也更新了RegexKitLite
但问题。没解决。欢迎任何建议谢谢你提前。
NSString* saddr = [NSString stringWithFormat:@"%f,%f", f.latitude, f.longitude];
NSString* daddr = [NSString stringWithFormat:@"%f,%f", t.latitude, t.longitude];
NSString* apiUrlStr = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=%@&destination=%@&sensor=false", saddr, daddr];
// http://maps.googleapis.com/maps/api/directions/json?origin=41.029598,28.972985&destination=41.033586,28.984546&sensor=false%EF%BB%BF%EF%BB%BF
NSURL *apiUrl = [NSURL URLWithString:[apiUrlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSLog(@"api url: %@", apiUrl);
NSString *apiResponse = [NSString stringWithContentsOfURL:apiUrl encoding:nil error:nil];
NSString* encodedPoints = [apiResponse stringByMatching:@"points:\\\"([^\\\"]*)\\\"" capture:1L];
NSLog(@"encodedPoints: %@", encodedPoints);
if (encodedPoints) {
return [self decodePolyLine:[encodedPoints mutableCopy]];
}
else {
return NO;
}
答案 0 :(得分:0)
我认为这不是同步执行API请求的好方法,尤其是当用户'手机连接不良,会降低应用程序的响应速度。因此,您应该使用NSURLSession
执行异步API请求。
此外,Directions API可能会为您的请求返回多个路由。因此,最好使用NSArray
来存储折线点。
示例代码:
- (void)getPolyline {
NSURL *url = [[NSURL alloc] initWithString:@"https://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=Los+Angeles,CA&key=YOUR_API_KEY"];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL: url];
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithRequest:request completionHandler:
^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (!error) {
NSError *jsonError;
NSDictionary *dict = (NSDictionary*)[NSJSONSerialization JSONObjectWithData:data options:nil error:&jsonError];
if (!jsonError) {
NSArray *routesArray = (NSArray*)dict[@"routes"];
NSMutableArray *points = [NSMutableArray array];
for (NSDictionary *route in routesArray) {
NSDictionary *overviewPolyline = route[@"overview_polyline"];
[points addObject:overviewPolyline[@"points"]];
}
NSLog(@"%@", points);
}
} else {
//print error message
NSLog(@"%@", [error localizedDescription]);
}
}] resume];
}