0

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)

}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Thanks guys both your answers works! by the way can i ask a question? how do i instantly show the direction route from my location to 1 Republic Boulevard , Singapore 038975 – Lim Ta Sheng Feb 05 '17 at 15:05

1 Answers1

0

Your URL is invalid. The spaces need to be escaped as %20:

URL(string: "http://maps.apple.com/maps?saddr=1%20Republic%20Boulevard,%20Singapore%20038975")!

Alternatively, use URLComponent + URLQueryItem to let the system escape it for you:

var components = URLComponents(string: "http://maps.apple.com/maps")!
components.queryItems = [URLQueryItem(name: "saddr", value: "1 Republic Boulevard, Singapore 038975")]
let url = components.url!
UIApplication.shared.openURL(url)
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005