如何在iOS SDK中根据邮政编码(ZIP)获取国家名称

3
通过提供用户的邮政编码来获取国家名称是否有可能?
我查看了Core Location框架,但似乎它不能通过提供邮政编码来查找国家名称。
Core Location框架(CoreLocation.framework)向应用程序提供位置和方向信息。对于位置信息,该框架使用内置的GPS、蜂窝或Wi-Fi收音机来查找用户当前的经度和纬度。
我希望iOS SDK有一个类可以实现这一功能,我真的不想使用Google Maps API之类的东西。
2个回答

4

是的,您可以在iOS SDK中找到解决方案。

将文本字段连接到此操作:

- (IBAction)doSomethingButtonClicked:(id) sender
{
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder geocodeAddressString:yourZipCodeGoesHereTextField.text completionHandler:^(NSArray *placemarks, NSError *error) {

        if(error != nil)
        {
            NSLog(@"error from geocoder is %@", [error localizedDescription]);
        } else {
            for(CLPlacemark *placemark in placemarks){
                NSString *city1 = [placemark locality];
                NSLog(@"city is %@",city1);
                NSLog(@"country is %@",[placemark country]);
                // you'll see a whole lotta stuff is available
                // in the placemark object here...
                NSLog(@"%@",[placemark description]);
            }
        }
    }];
}

我不确定iOS是否支持所有国家的邮政编码,但它肯定适用于英国(例如“YO258UH”)和加拿大(“V3H5H1”)。


2

Michael Dautermann的回答是正确的,如果有人来到这篇文章寻找Swift (v4.2)的代码,请看下面:

Original Answer翻译成"最初的回答"

@IBAction func getLocationTapped(_ sender: Any) {

    guard let zipcode = zipcodeTxtField.text else {
        print("must enter zipcode")
        return
    }

    CLGeocoder().geocodeAddressString(zipcode) { (placemarks, error) in
        if let error = error{
            print("Unable to get the location: (\(error))")
        }
        else{
            if let placemarks = placemarks{

                // get coordinates and city
                guard let location = placemarks.first?.location, let city = placemarks.first?.locality else {
                    print("Location not found")
                    return
                }


                print("coordinates: -> \(location.coordinate.latitude) , \(location.coordinate.longitude)")
                print("city: -> \(city)")

                if let country = placemarks.first?.country{
                     print("country: -> \(country)")
                }

                //update UI on main thread
                DispatchQueue.main.async {
                    self.countryLbl.text = country
                }
            }
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接