[Xcode10 實際操作]八、網路與多執行緒-(6)使用UIApplication物件開啟地圖
阿新 • • 發佈:2018-12-02
本文將演示如何使用應用程式單例物件,開啟地圖的功能。
在專案導航區,開啟檢視控制器的程式碼檔案【ViewController.swift】
1 import UIKit 2 3 class ViewController: UIViewController { 4 5 override func viewDidLoad() { 6 super.viewDidLoad() 7 // Do any additional setup after loading the view, typically from a nib.8 //呼叫方法,開啟地圖 9 openMap() 10 } 11 12 //建立一個方法,實現開啟地圖的功能 13 func openMap() 14 { 15 //首先建立一個字串變數,設定地圖顯示的目標地理位置 16 var address = "Shenzhen" 17 //對字串進行編碼,使地圖能夠解析到正確的地理位置 18 address = address.addingPercentEncoding(withAllowedCharacters: CharacterSet())! 19//建立一個字串常量,呼叫谷歌地圖的相關介面 20 let urlText = "https://maps.google.cn/maps?q=\(address)" 21 //然後將字串轉換為網址物件 22 let url = URL(string: urlText) 23 //獲取應用程式單例物件, 24 //使用它開啟網頁的功能, 25 //開啟指定網址的網頁。 26 UIApplication.shared.openURL(url!) 27 } 28 29 overridefunc didReceiveMemoryWarning() { 30 super.didReceiveMemoryWarning() 31 // Dispose of any resources that can be recreated. 32 } 33 }