gpt4 book ai didi

ios - Swift 在不同 View 中捕获异步函数

转载 作者:行者123 更新时间:2023-11-28 15:44:59 27 4
gpt4 key购买 nike

我有一个异步函数 (geocodeAddressString),它在 prepare for segue 函数中被调用。问题是这个异步函数在执行 segue 之后返回。下面的异步函数将地址字符串转换为坐标。我无法在此准备功能之前调用此异步功能,因为用户可以随时编辑用户地址字段。我试过在按下保存按钮时调用异步函数,然后在异步函数返回时对 segue 进行编码,但是按下按钮和发生 segue 之间的加载时间太长。

所以我的问题是,是否有任何方法可以在新 View 中捕获此异步方法?然后我可以用实际返回的值替换一些临时坐标。感谢任何帮助,谢谢!

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {    
//convert address to coordinates
let geoCoder = CLGeocoder()
geoCoder.geocodeAddressString(addressTxt.text!) { (placemarks, error) in
guard
let placemarks = placemarks,
let location = placemarks.first?.location
else {
// handle no location found
return
}

let tempCoord = CLLocationCoordinate2D(latitude: (location.coordinate.latitude), longitude: (location.coordinate.longitude))
self.donatedItem = DonatedItem(self.titleTxt.text!, self.itemImg.image!, self.donated, self.descTxt.text!, expirationDate, tempCoord, (user?.uid)!, (self.donatedItem?.itemID)!, self.addressTxt.text!, reserved: false, reservedBy: "NA")
self.donatedItem?.updateItem()
}

switch(segue.identifier ?? "") {
case "saveItem":

homeViewController.isReturningSegue = true
homeViewController.tempItem = self.donatedItem

default:
print("Undefined segue")
}
}

最佳答案

当然可以。发布通知以通知新 View 。或者使用闭包。例如,这是通知。

NotificationCenter.default.post(name: Notification.Name(rawValue: "locationUpdated"), object: coordinate)

这是使用闭包的方法。

typealias closure = (String) -> Void

class A: UIViewController {
var coordinateUpdated: closure? // call this after coordinate updated

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let b = segue.destination as? B {
coordinateUpdated = b.coordinateUpdated
}
}
}

class B: UIViewController {
let coordinateUpdated: closure = { (coordinate: String) in
// update here
}


}

关于ios - Swift 在不同 View 中捕获异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43220200/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com