【发布时间】:2017-04-26 14:15:04
【问题描述】:
我正在尝试使用 Google Maps API 获取两个位置之间的行车/步行距离。我正在将我的应用程序从 Objective-c 更新到 Swift 3,现在我一直坚持将这段代码转换为 Swift 3。
NSString *dist;
NSString *strUrl = [NSString stringWithFormat:@"http://maps.googleapis.com/maps/api/directions/json?origin=%f,%f&destination=%f,%f&sensor=false&mode=%@", closestLocation.coordinate.latitude, closestLocation.coordinate.longitude, _currentUserLocation.coordinate.latitude, _currentUserLocation.coordinate.longitude, @"DRIVING"];
NSURL *url = [NSURL URLWithString:[strUrl stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLQueryAllowedCharacterSet]];
NSData *jsonData = [NSData dataWithContentsOfURL:url];
if(jsonData != nil)
{
NSError *error = nil;
id result = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
NSMutableArray *arrDistance=[result objectForKey:@"routes"];
if ([arrDistance count]==0) {
NSLog(@"N.A.");
}
else{
NSMutableArray *arrLeg=[[arrDistance objectAtIndex:0]objectForKey:@"legs"];
NSMutableDictionary *dictleg=[arrLeg objectAtIndex:0];
dist = [NSString stringWithFormat:@"%@",[[dictleg objectForKey:@"distance"] objectForKey:@"text"]];
}
}
else{
NSLog(@"N.A.");
}
我尝试使用 Swiftify 之类的工具,但处处出错。我现在拥有的是:
var dist: String = ""
var strUrl: String = "http://maps.googleapis.com/maps/api/directions/json?origin=\(closestLocation!.coordinate.latitude),\(closestLocation!.coordinate.longitude)&destination=\(currentUserLocation!.coordinate.latitude),\(currentUserLocation!.coordinate.longitude)&sensor=false&mode=\("DRIVING")"
var url = URL(string: strUrl)
var jsonData = Data(contentsOf: url!)
if (jsonData != nil) {
var error: Error? = nil
var result: Any? = try? JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.Element.mutableContainers)
var arrDistance: [Any]? = (result?["routes"] as? [Any])
if arrDistance?.count == 0 {
print("N.A.")
}
else {
var arrLeg: [Any]? = ((arrDistance?[0] as? [Any])?["legs"] as? [Any])
var dictleg: [AnyHashable: Any]? = (arrLeg?[0] as? [AnyHashable: Any])
dist = "\(dictleg?["distance"]["text"])"
}
}
else {
print("N.A.")
}
我现在的错误如下:
使用 Data(contentsOf: url!) 它告诉我“调用可以抛出,但它没有标有 'try' 并且错误未处理
而且它不喜欢我如何将 [Any] 用于我的 arrDistance 变量。
如果有人知道如何在 Swift 3 中实现这个 API 调用,那将非常有帮助。谢谢
【问题讨论】:
-
与问题无关,但您不应使用 Data(contentsOf: url!) 下载数据。你应该使用 URLSession
dataTask(with: URL) -
但是你为什么使用谷歌的 API 而不是苹果内部的?
标签: swift google-maps swift3