gpt4 book ai didi

ios - 按下 UILabel 时分配变量值以打开 Apple Maps 的问题

转载 作者:可可西里 更新时间:2023-11-01 00:54:07 25 4
gpt4 key购买 nike

本质上,我正在解析 JSON 数据并将其分配给一个名为 addressPressNow 的变量,然后我有以下函数在用户点击 UILabel 时执行:

目标是打开 Apple Maps,提供它包含的变量值。

因为我正在为变量分配地址,所以它将包含空格例如:3981 试驾 Cupertino CA 95014

注意:变量的值被正确传递,因为当我在 func tapFunction 中执行 print(addressPressNow) 时它打印正确。

@objc
func tapFunction(sender:UITapGestureRecognizer) {

let targetURL = NSURL(string: "http://maps.apple.com/?q=" + addressPressNow)!


UIApplication.shared.openURL(targetURL as URL)

}

问题是我无法将变量应用于字符串 URL,并出现以下错误:

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

以下是我如何为变量赋值:

struct FacilityInfo: Decodable {
let address: String

class infoViewController: UIViewController {

var addressPressNow : String = ""

override func viewDidLoad() {
super.viewDidLoad()



let tap = UITapGestureRecognizer(target: self, action: #selector(infoViewController.tapFunction))
addressInfo.isUserInteractionEnabled = true
addressInfo.addGestureRecognizer(tap)


let url = URL(string: "https://test/test/example”)!

let task = URLSession.shared.dataTask(with: url) { data, response, error in

// ensure there is no error for this HTTP response
guard error == nil else {
print ("error: \(error!)")
return
}

// ensure there is data returned from this HTTP response
guard let data = data else {
print("No data")
return
}

// Parse JSON into array of Car struct using JSONDecoder


guard let cars = try? JSONDecoder().decode([FacilityInfo].self, from: data), let secondCar = cars.first
else {
print("Error: Couldn't decode data into cars array")
return
}
DispatchQueue.main.async {
self.addressPressNow = secondCar.facility_address
}

}

最佳答案

“我正在为一个包含空格的变量分配一个地址”

如果地址包含空格,那么使用该字符串创建 NSURL 将会崩溃。您可以使用 addingPercentEncoding解决问题

if let encodedAddress = addressPressNow.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
let targetURL = NSURL(string: "http://maps.apple.com/?q=" + encodedAddress)!
UIApplication.shared.openURL(targetURL as URL)
}

并且不要使用 NSURL 并强制解包。像这样更新

if let encodedAddress = addressPressNow.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
let targetURL = URL(string: "http://maps.apple.com/?q=" + encodedAddress) {
UIApplication.shared.openURL(targetURL)
}

根据 matt 使用的建议 URLComponents

let addressPressNow = "3981 Test Drive Cupertino CA 95014"
var components = URLComponents(string: "http://maps.apple.com")
components?.queryItems = [URLQueryItem(name: "q", value: addressPressNow)]
print(components?.url)//http://maps.apple.com?q=3981%20Test%20Drive%20Cupertino%20CA%2095014
if let targetURL = components?.url {
UIApplication.shared.open(targetURL, options: [:], completionHandler: nil)
}

关于ios - 按下 UILabel 时分配变量值以打开 Apple Maps 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56079606/

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