为什么CLGeoCoder无法获得任何东西?

时间:2018-07-09 12:01:54

标签: swift location clgeocoder

我已经编写了一个类,可以将位置反向转换为地理信息,如下所示:

import Foundation
import UIKit
import CoreLocation
public class Geocoder{
    public static func Geocoder(latitudein:Double,longitudein:Double)->String
    {
        var address:String?="";
        var geocoder = CLGeocoder.init();
        var location:CLLocation=CLLocation.init(latitude: latitudein, longitude: longitudein);

       // var placemarks:[CLPlacemark]=[CLPlacemark].init();
        geocoder.reverseGeocodeLocation(location) { (placemarks, error) in
            for p in placemarks!
            {
                if(p != nil)
                {
                    //print(p);
                   // address?.append(p.country!);
                   // address?.append(p.subAdministrativeArea!);
                    address=p.name;
                }
            }

        }
        print(address);
        return address!;
    }
}

但是地址是nil,我已经尝试过p.country和许多其他参数,但是仍然返回nil,我想问为什么以及如何解决它?

1 个答案:

答案 0 :(得分:0)

您可以尝试

public static func Geocoder(latitudein:Double,longitudein:Double,completion:@escaping(_ address:String?) -> Void )
{

    var geocoder = CLGeocoder.init();
    var location:CLLocation=CLLocation.init(latitude: latitudein, longitude: longitudein);

    geocoder.reverseGeocodeLocation(location) { (placemarks, error) in


       if error != nil {
           completion(nil)
           return
        } 

        for p in placemarks!
        {
            if(p != nil)
            {
                completion(p.name)
                break
            }
        }

    }

}

override func viewDidLoad() {
    super.viewDidLoad()

    VCName.Geocoder(latitudein: 20.555, longitudein: 30.777) { (address) in
        if let ad = address {


        }
    }

}