I’ve written a Swift 3 SDK for Particle that does nearly all I want, but I can’t get publish to work. I’ve looked at a bunch of sources, but I just can’t get the syntax right. I checked out the Particle official SDK, but got lost in all the AFNetworking code, and couldn’t actually find where they create the final request. This is what I’ve tried (along with numerous variations).
func publishEvent(name: String, data: String, isPrivate: Bool, ttl: Int, completionHandler: @escaping (_ error:Error?) -> Void) {
let url = URL(string: "https://api.particle.io/devices/events")
var postRequest = URLRequest(url: url!, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: 10)
postRequest.httpMethod = "POST"
postRequest.setValue("Bearer \(accessToken!)", forHTTPHeaderField: "Authorization")
let privateString = isPrivate ? "true" : "false"
let bodyData = "name=\(name)&data=\(data)&private=\(privateString)&ttl=\(ttl)"
postRequest.httpBody = bodyData.data(using: String.Encoding.utf8)
session = URLSession.shared
let dataTask = session.dataTask(with: postRequest) {data, response, taskError in
print(response!)
if (taskError == nil) {
do {
if let infoDict = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as? [String:AnyObject] {
print("infoDict is: \(infoDict)")
//completionHandler(infoDict["error"] as! Error?)
}
} catch let jsonError as NSError {
print(jsonError.localizedDescription)
}
}else{
print("taskError from executeFunction func is: \(taskError!.localizedDescription)")
}
}
dataTask.resume()
}
The result I get is,
[“ok”: 0, “error”: Not Found]