学习笔记|swift4--使用URLSession进行网络请求
这里写了怎么拿到json数据
不知道怎么解析的小伙伴可以看我另一篇贴子 《 swift4--解析json》 【学习笔记|swift4--使用URLSession进行网络请求】
GET请求:
//
//ViewController.swift
//URLSesstionTest
//import UIKitclass 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.
}}
POST请求:
func post(name:String,password:String) {let session = URLSession(configuration: .default)
// 设置URL(该地址不可用,写你自己的服务器地址)
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"
// 设置要post的内容,字典格式
let postData = https://www.it610.com/article/["name":"\(name)","password":"\(password)"]
let postString = postData.compactMap({ (key, value) -> String in
return "\(key)=\(value)"
}).joined(separator: "&")
request.httpBody = postString.data(using: .utf8)
// 后面不解释了,和GET的注释一样
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()
}
推荐阅读
- EffectiveObjective-C2.0|EffectiveObjective-C2.0 笔记 - 第二部分
- 由浅入深理解AOP
- 继续努力,自主学习家庭Day135(20181015)
- python学习之|python学习之 实现QQ自动发送消息
- Android中的AES加密-下
- 一起来学习C语言的字符串转换函数
- 定制一套英文学习方案
- 漫画初学者如何学习漫画背景的透视画法(这篇教程请收藏好了!)
- 《深度倾听》第5天──「RIA学习力」便签输出第16期
- 如何更好的去学习