我有一个控制某些IoT设备的应用。我正在尝试使用evrythng API做旧的iHome插座。需要采取这样的命令:
curl -X PUT \
https://api.evrythng.com/thngs/<DEVICE_ID>/properties/targetpowerstate1 \
-H 'authorization: MY_API_KEY' \
-H 'cache-control: no-cache' \
-H 'content-type: application/json' \
-d '[{"value":"1"}]'
问题在于,由于方括号内的花括号,[{“ value”:“ 1”}]尝试使用alamofire作为参数发送时不起作用。所以我尝试使用NSMutableURLRequest做类似的事情:
let url = URL(string: "https://api.evrythng.com/thngs/\(self.id)/properties/targetpowerstate1")
let request = NSMutableURLRequest(url: url!)
let session = URLSession.shared
let stringParams = "[{\"value\":\"0\"}]"
request.httpBody = stringParams.data(using: String.Encoding.utf8)
request.httpMethod = "PUT"
request.addValue("no-cache", forHTTPHeaderField: "cache-control")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue(apikey, forHTTPHeaderField: "Authorization")
let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
guard error == nil else {
getvcfunc.statusMsg(error! as! String)
return
}
guard let data = data else {
getvcfunc.statusMsg("Data is empty")
return
}
let outputStr = String(data: data, encoding: String.Encoding.utf8)
getvcfunc.statusMsg(outputStr ?? "no value")
})
task.resume()
请帮助我,我已经尝试了好几个小时了,只是想弄清楚如何使用大括号发送此PUT请求。