这里写了怎么拿到json数据
GET请求:
import UIKit
class ViewController: UIViewController {
var keyWord:String?
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()
keyWord = "许嵩"
if keyWord == nil {
print("啥都没输呢")
}
else {
urlString = urlString + keyWord!
}
let newUrlString = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
let config = URLSessionConfiguration.default
let url = URL(string: newUrlString!)
let request = URLRequest(url: url!)
let session = URLSession(configuration: config)
let task = session.dataTask(with: request) { (data,response,error) in
let dictionary = try? JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
print(dictionary!)
}
task.resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
POST请求:
func post(name:String,password:String) {
let session = URLSession(configuration: .default)
let url = "http://66.666.666.666/"
var request = URLRequest(url: URL(string: url)!)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
let postData = ["name":"\(name)","password":"\(password)"]
let postString = postData.compactMap({ (key, value) -> String in
return "\(key)=\(value)"
}).joined(separator: "&")
request.httpBody = postString.data(using: .utf8)
let task = session.dataTask(with: request) {(data, response, error) in
do{
if let jsonObj:NSDictionary = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions()) as? NSDictionary
{
print(jsonObj)
DispatchQueue.main.async{
}
}
} catch{
print("Error.")
DispatchQueue.main.async{
}
}
}
task.resume()
}