【发布时间】:2021-11-02 08:04:19
【问题描述】:
当我按下 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()
}
【问题讨论】:
-
就写吧。 “DispatchQueue.main.async { self.navigationController?.pushViewController(nc, animated: true) }” 代替 self.navigationController?.pushViewController(nc, animated: true)
-
紫色表示你有一个保留周期。如果您向搜索引擎询问确切的警告信息,您还能找到什么?