[英]UIViewController.navigationController must be used from main thread only
当我按下 UIbutton 时,出现紫色错误,提示“UIViewController.navigationController 必须仅从主线程使用”。 我对这种语言有点陌生,所以有人能告诉我为什么要解决这个问题吗?
@IBAction func searchButtonPressed(_ sender: UIButton) {
let houseNo = field.text
let wardNo = wardnoDropdown.text
let afterURL = "house_no=\(houseNo ?? "")&ward_no=\(wardNo ?? "")"
let escapedString = afterURL.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) ?? ""
let finalURL = "\(searchURL)\(escapedString)"
let nc = self.storyboard?.instantiateViewController(identifier: "MapViewController") as! MapViewController
func performRequest(){
//1.create URL
if let url = URL(string: finalURL){
//2.Create URL session
let session = URLSession(configuration: .default)
//3.Give session a Task
let task = session.dataTask(with: url) { (data, response, error) in
if error != nil{
print("error")
return
}
if let safeData = data{
let decoder = JSONDecoder()
do{
let decodedData = try decoder.decode(CordinateData.self, from: safeData)
let lat = decodedData.data[0].x
let lon = decodedData.data[0].y
let doubleLat = Double(lat) ?? 0.0
let doubleLon = Double(lon) ?? 0.0
nc.lon = doubleLon
nc.lat = doubleLat
self.navigationController?.pushViewController(nc, animated: true)
//self.present(nc, animated: true, completion: nil)
print(doubleLat)
print(doubleLon)
}catch{
print("error")
}
}
}
//Start the task
task.resume()
}
}
performRequest()
}
将您的视图控制器从main thread
添加到 navigationController 作为 -
do{
let decodedData = try decoder.decode(CordinateData.self, from: safeData)
let lat = decodedData.data[0].x
let lon = decodedData.data[0].y
let doubleLat = Double(lat) ?? 0.0
let doubleLon = Double(lon) ?? 0.0
nc.lon = doubleLon
nc.lat = doubleLat
DispatchQueue.main.async {
self.navigationController?.pushViewController(nc, animated: true)
//self.present(nc, animated: true, completion: nil)
}
print(doubleLat)
print(doubleLon)
}catch{
print("error")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.