Lim Ta Sheng Lim Ta Sheng - 4 years ago 197
Swift Question

Xcode 8 open new apple map

Need some help.This is my code below, when i click button GoMap, i was prompted this error
fatal error: unexpectedly found nil while unwrapping an Optional value

@IBAction func GoMap(_ sender: UIButton) {
UIApplication.shared.openURL(NSURL(string: "http://maps.apple.com/maps?saddr=1 Republic Boulevard , Singapore 038975")! as URL)

}

Answer Source

Your url contains space and special character so you need to encode your URL. Also in Swift 3 use native URL type instead of NSURL.

let stringUrl = "http://maps.apple.com/maps?saddr=1 Republic Boulevard , Singapore 038975"
if let encodedURLString = stringUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
    let url = URL(string: encodedURLString) {
    UIApplication.shared.openURL(url)
}

Edit: For that change your url like this way.

let stringUrl = "http://maps.apple.com/maps?saddr=Current Location&daddr=1 Republic Boulevard , Singapore 038975"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download