需求:1,带header。2,接收的是json数据。如图所示
1,下面将获取“result”值
import Foundation
import Network
class DeviceCtrl: ObservableObject {
//URL,,改成你的
private static var thingsCloud = "https://pi.iot-api.com/app/device/v1/teabvlq/attributes"
//调用该方法就会进行网络请求
func getJSON() {
guard let thingsCloud = URL(string: Self.thingsCloud) else { return }
var request = URLRequest(url: thingsCloud)
request.addValue("application/json", forHTTPHeaderField: "Content-Type") //header1
request.addValue("tCfWNEZ", forHTTPHeaderField: "Project-Key") //header2
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if(data != nil) {
if let json = try? JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as? [String : Any] {
let resultJSON = json["result"]! as AnyObject //这里是关键
print(resultJSON) //打印出来就是1了
}
} else {
print("数据是空的")
}
}
task.resume()
}
2,下面将获取“attributes”里面的任意一个值,以temperature为例
import Foundation
import Network
class DeviceCtrl: ObservableObject {
//替换你的
private static var thingsCloud = "https://gpi.iot-api.com/app/device/v1/teabclq/attributes"
func getJSON() {
guard let thingsCloud = URL(string: Self.thingsCloud) else { return }
var request = URLRequest(url: thingsCloud)
request.addValue("application/json", forHTTPHeaderField: "Content-Type") //替换你的header1
request.addValue("tCfWNEZ", forHTTPHeaderField: "Project-Key")//替换你的header2
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if(data != nil) {
if let json = try? JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as? [String : Any] {
let attributesJSON = json["attributes"]! as AnyObject
//获取attributes里面的数据
if let nodeJSON = try? JSONSerialization.data(withJSONObject: attributesJSON, options: []) {
let node = try? JSONSerialization.jsonObject(with: nodeJSON, options: .mutableContainers) as AnyObject
//关键点来了,这里是获取temperature
print("\(String(describing: node!["temperature"]))")
}
}
} else {
print("数据是空的")
}
}
task.resume()
}