我正在使用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'并且错误未处理”
它不喜欢我将[任何]用于我的arrDistance变量。
如果有人知道如何在Swift 3中实现此API调用,那将非常有帮助。谢谢
dataTask(with: URL)
。 - Leo Dabus