[Xcode 實際操做]8、網絡與多線程-(6)使用UIApplication對象打開地圖

目錄:[Swift]Xcode實際操做html

本文將演示如何使用應用程序單例對象,打開地圖的功能。swift

在項目導航區,打開視圖控制器的代碼文件【ViewController.swift】ide

 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     override func didReceiveMemoryWarning() {
30         super.didReceiveMemoryWarning()
31         // Dispose of any resources that can be recreated.
32     }
33 }
相關文章
相關標籤/搜索