先在專案的info.plist 的最下面加入這兩個設定
func downloadMovise(url:String){
if let okurl = URL(string: url){
//let request = NSMutableURLRequest(url: okurl)
let task = URLSession.shared.dataTask(with: okurl, completionHandler: { (data, response,
error) in
if error != nil{
}else{
if let urlContent = data{
do{
let jsonresult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers)
print(jsonresult)
}catch{
print(error.localizedDescription)
}
}
}
})
task.resume()
}
}
流程是這樣
string -> url -> 呼叫 RLSession.shared.dataTask(with url, {...}) -> task.resume
// string -> url
if let okurl = URL(string: url){}
// url -> task
let task = URLSession.shared.dataTask(with: okurl, completionHandler: { (data, response,
error) in
// 先判斷error
if error != nil{
}else{
//data就是download下來的資料...
// 先解開 optional... -> urlContent
// 然後在呼叫 JSONSerialization.jsonObject
// 由於他是會throws , 所以要用 do catch 的方式
if let urlContent = data{
do{
let jsonresult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers)
print(jsonresult)
}catch{
print(error.localizedDescription)
}
}
}
})
沒有留言:
張貼留言