这里写了怎么拿到json数据
不知道怎么解析的小伙伴可以看我另一篇贴子 《 swift4--解析json》
//
// ViewController.swift
// URLSesstionTest
//
import UIKit
class ViewController: UIViewController {
// 要传递的参数
var keyWord:String?
// qq音乐搜索接口
var urlString:String = "http://s.music.qq.com/fcgi-bin/music_search_new_platform?t=0&%20n=3&aggr=1&cr=1&loginUin=0&format=json&%20inCharset=GB2312&outCharset=utf-8¬ice=0&%20platform=jqminiframe.json&needNewCode=0&p=1&catZhida=0&%20remoteplace=sizer.newclient.next_song&w="
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
keyWord = "许嵩"
if keyWord == nil {
print("啥都没输呢")
}
else {
urlString = urlString + keyWord!
}
// 加密,当传递的参数中含有中文时必须加密
let newUrlString = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
//创建请求配置
let config = URLSessionConfiguration.default
// 创建请求URL
let url = URL(string: newUrlString!)
// 创建请求实例
let request = URLRequest(url: url!)
// 进行请求头的设置
// request.setValue(Any?, forKey: String)
// 创建请求Session
let session = URLSession(configuration: config)
// 创建请求任务
let task = session.dataTask(with: request) { (data,response,error) in
// print(String(data: data! , encoding: .utf8) as Any)
// 将json数据解析成字典
let dictionary = try? JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
print(dictionary!)
}
// 激活请求任务
task.resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
会返回如下的数据: