Accessing Data From Event in Swift

Hi, I created an event called “checkTemp” on my Photon that publishes the temperature of my room. I used this in terminal : curl https://api.particle.io/v1/events/checkTheTemp?access_token=“access-token” and it worked( i removed the access token). Now, I am trying to access the data that the event publishes in swift.

I used this in XCode
let cool = SparkCloud.sharedInstance().subscribeToDeviceEventsWithPrefix(“checkTheTemp”, deviceID: “device-ID”, handler: self.handler)

How do I get the data from the event? That way I can display it on my app.

You get the data from your handler. How have you defined that? A SparkEvent should be passed in to that handler, and you get the data from event.data.

I wasn’t sure how to declare the handler. I just said var handler : SparkHandler?. The Particle documentation shows it in Objective C and I was unsure how to translate that to Swift

I think something like this should work,

class SparkTestViewController: UIViewController {

    var eventHandler: ((event: SparkEvent!, error: NSError!) -> Void)!
    
    
        @IBAction func subscribeButton(sender: UIButton) {
            eventHandler = {(event: SparkEvent!, error: NSError!) -> Void in
                if error == nil {
                    dispatch_async(dispatch_get_main_queue()) { () -> Void in
                        print("data is: \(event.data)")
                    }
                }else{
                    print(error.description)
                }
            }
        
            let cool = SparkCloud.sharedInstance().subscribeToDeviceEventsWithPrefix("checkTheTemp", deviceID: "deviceID", handler: eventHandler)
        }
}

That is more or less a translation of the code from Particle’s sample app. I think you could also do it without creating the var at the top of the file, as I showed above, and include the signature of the closure right in line with the function,

let cool = SparkCloud.sharedInstance().subscribeToDeviceEventsWithPrefix("checkTheTemp", deviceID: "deviceID") { (event: SparkEvent!, error: NSError!) in
            
    if error == nil {
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            print("data is: \(event.data)")
        }
    }else{
            print(error.description)
    }
}