[網路應用] Foundation — 透過 URL 取得網站文字訊息教學
資策會 APP Developer 行動開發工程師養成班
Published in
Jan 1, 2022
▍URL
- 是 Swift 中用來指定資源的物件
- 資源可以是手機內的檔案、網路的文字或是圖片
- URL(String)
- 本機資料:Local 檔案(fIle)
- 遠端資料:File transfer protocol(FTP)
- http:// or https://
3. 取得網路文字內容: String(contentsOf: , encoding:)
4.取得任何內容: Data(contentsOf:) , 舉例:圖片檔案下載
- String & Data 是不同的 Init 方法
▍Apple 官方 init(contentsOf:) 教學
▍使用Google Map API (Geocoding API) 得到點位縣市鄉鎮資料
google geocode URL
URL: https://iosnetworkdemo.appspot.com/address.jsp?address=
▍URLEncoding 中文處理
送中文參數給對方網站時,要自己先轉換
在轉換的過程,瀏覽器會幫忙做到這件事情,不需要自己做
若透過程式連到對方的網站,就需要自己轉換~
var address = “台北市”address = address.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
將中文字轉成 URL 可以讀取的格式;借用同樣的變數 address,透過借用的方式少寫一個變數
let encodedURL = "https://iosnetworkdemo.appspot.com/address.jsp?address="+address)
?後面是參數,在 PHP 為 key value 資訊
if let url = URL(string: “https://iosnetworkdemo.appspot.com/address.jsp?address=\(address)")
將 "台北市" 改寫成轉換過後的文字格式 \(address)
取得資料的過程中有可能會發生錯誤,在程式碼中撰寫 try,當錯誤發生時會自動先執行 catch 內的程式碼,詳細可以參考這一篇內的 do-try-catch 解說
do-try-catch 內的 let textView = UITextView(frame:self.view.bounds) 先作為示範教學,實際上還是建議用 storyboard 拉取 textView 喔!
URL 執行結果:網站回傳的 JSON 資料格式