ReverseGeocodeLocation在viewDidLoad()中完成使用swift4.1

时间:2018-05-07 15:56:35

标签: ios swift reverse-geocoding completionhandler

Swift版本:4.1

您好,我在swift中比初学者多一点。在“按用户位置订购应用程序”中工作。在用户下订单之前,我通过reversegeocodelocation function控制用户“国家/地区”和“城市”名称。并在firebase实时数据库子项中写入这些值。

我的数据结构就像

 -TR
   -Ankara
       -userID
           -Order(consist of user lat, user long, user mail, userOrder)

我可以做到,用户可以订购并取消他/她的订单。但我还想检查用户是否关闭手机并返回应用程序,应用程序应检查数据库,如果当前用户uID提供了订单,则必须更改按钮标签buttonToCancelState = true,我们吉祥物的形象。

这就是我获取订单的用户coord以及数据结构名称的“countrycode”和“city”的方式。

 func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    let location = locations [0]

    if let coord = manager.location?.coordinate {
        userLocation = coord

    }


    let geoCoder = CLGeocoder()
    geoCoder.reverseGeocodeLocation(location) {(placemark, error) in
        if error != nil {
            print("there is an error")
        } else {

        var placeMark: CLPlacemark?
        placeMark = placemark?[0]


        // City
        if let city = placeMark?.locality {
            self.userCity = city as String

        }

        // Country
        if let country = placeMark?.isoCountryCode {
            self.userCountry = country as String
            }
        }
    }
}

我在“订单按钮”中使用这些“国家”和“城市”作为例子;

            orderHasBeenCalled = true
            buttonLabelText.text = "CANCEL/EDIT"
            imgView.image = UIImage(named: "...")
            let orderRequestDictionary: [String:Any] = ["..."]
            databaseREF.child(userCountry).child(userCity).child(userID!).setValue(orderRequestDictionary)

它完美无瑕地用户可以发送订单,即使用户退出也删除它,(整个代码不包括在内)

现在的问题是,我想检查用户是否在viewDidLoad()为此加载

时加载了订单
if let userID = FirebaseAuth.Auth.auth().currentUser?.uid {
        databaseRef.child(userCountry).child(userCity).queryOrdered(byChild: userID!).observe(.childAdded, with: { (snapshot) in
            self.OrderHasBeenCalled = true
            self.buttonLabelText.text = "CANCEL/EDIT"
            self.imgView.image = UIImage(named: "...")
            databaseRef.child(self.userCountry).child(self.userCity).removeAllObservers()
        })
   }

现在问题是因为我在互联网上阅读reversegeocode是异步的或类似的东西,并且似乎它没有准备好当viewDidLoad()加载,“检查是否有订单的代码”使应用程序崩溃,因为它没有找到值来搜索孩子们的名字。

Terminating app due to uncaught exception 'InvalidPathValidation', reason: '(child:) Must be a non-empty string and not contain '.' '#' '$' '[' or ']''

要在orderbutton中使用userCountry和userCity,我在viewDidLoad()

之前定义它们
var userCountry = String()
var userCity = String()

我尝试了很多方法,但没有真正弄清楚如何在viewdidload()中完成reversegeocode的完成。我也尝试了viewDidAppear(),但它也给了userCountry()和userCity()nil。

我希望我的问题清楚易懂。如果答案是这样的,将非常感激。在互联网上做了很多研究,有些我不明白或者不知道我怎么能尝试。我希望闪耀的最后一个地方是堆栈溢出。感谢所有善良回应我问题的人。

1 个答案:

答案 0 :(得分:0)

我会改变一点方法。使用异步功能后,您必须避免同步请求值。

有几种方法可以从异步函数进行嵌套调用,从我的代码到达这种方法,适应你的需要,它应该工作。

/////////attention the scope (must be above class declaration)
typealias CompletionGetAddress = (_ userCity : String?, _ userCountry: String?, _ success: Bool) -> Void
var userLocation = CLLocationCoordinate2D()
var locationManager = CLLocationManager()
//

class viewController: ... {
func viewDidLoad() {

    yourLocationManager.requestLocation()

    // you should implement some code to ensure your userLocation from your locationManager is not nil and a valid location

    if let userID = FirebaseAuth.Auth.auth().currentUser?.uid {
        if self.userCity != "" {
            databaseRef.child(userCountry).child(userCity).queryOrdered(byChild: userID!).observe(.childAdded, with: { (snapshot) in
                self.OrderHasBeenCalled = true
                self.buttonLabelText.text = "CANCEL/EDIT"
                self.imgView.image = UIImage(named: "...")
                databaseRef.child(self.userCountry).child(self.userCity).removeAllObservers()
            })
        } else {
            getAddress { (city, country, success) in
                if success {
                    self.userCity = city
                    self.userCountry = country
                    databaseRef.child(userCountry).child(userCity).queryOrdered(byChild: userID!).observe(.childAdded, with: { (snapshot) in
                        self.OrderHasBeenCalled = true
                        self.buttonLabelText.text = "CANCEL/EDIT"
                        self.imgView.image = UIImage(named: "...")
                        databaseRef.child(self.userCountry).child(self.userCity).removeAllObservers()
                    })
                }
            }           
        }
    }
} 
}


func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    let location = locations [0]

    if let coord = manager.location?.coordinate {
        userLocation = coord /// attention here 

    }
}


func getAddress(completion: @escaping CompletionGetAddress) {
    let geoCoder = CLGeocoder()
    geoCoder.reverseGeocodeLocation(userLocation) {(placemark, error) in
        if error != nil {
            print("there is an error")
            completion(nil, nil, false)
        } else {
            var city: String = ""
            var country: String = ""
            var placeMark: CLPlacemark?
            placeMark = placemark?[0]
            // City
            if let c = placeMark?.locality {
                city = c
            }
            // Country
            if let c = placeMark?.isoCountryCode {
                country = c
            }
            completion(city, country, true)
        }
    }
}