Data retrieval with Swift

I followed your example code from your blogs a-feature-a-day series to fetch data from my 1st Backendless app (using Swift). My app has a table “Media_Event”. I want to fetch all records. When I try to compile the app with your example code I get the compiler error (on line 38 in the code below):

Value of type 'AnyObject' has no member 'deviceName'

Here are my class and the method that fetch records. Note that I needed to cast the event as my Media_Event class to access event.deviceName. Also note your example code uses println() where it should now just be print(). Am I missing something?

import Foundation


class Media_Event: NSObject {
    
    var objectId : String?
    var created : NSDate?
    var updated : NSDate?
    
    var appName: String?
    var deviceName: String?
    var mediaName: String?
    
    class func MediaEventWithAppName(appName: String, deviceName: String, mediaName: String) -> Media_Event {
        let newMediaEvent = Media_Event()
        newMediaEvent.appName = appName
        newMediaEvent.deviceName = deviceName
        newMediaEvent.mediaName = mediaName
        
        return newMediaEvent
    }
    
}




@IBAction func getMediaEvents(sender: AnyObject) {
        
    backendless.persistenceService.of(Media_Event.ofClass()).find(
        BackendlessDataQuery(),
        response: { (events : BackendlessCollection!) -> () in
             let currentPage = events.getCurrentPage()
            print("Loaded \(currentPage.count) Media_Event objects")
            print("Total Media_Events in the Backendless starage: \(events.totalObjects)")
                
            for event in currentPage {
            	// Had to cast the object to avoid compiler error
                let theEvent: Media_Event = event as! Media_Event
                 print("DeviceName = \(theEvent.deviceName!)") // works
                 print("DeviceName = \(event.deviceName!)") // this line errors without the cast
             }
        },
        error: { (fault : Fault!) -> () in
            print("Server reported an error: \(fault)")
    })
}

Hi Jay,

Individual objects from the returned collection need to be cast to the specific type - just like you’re doing it on line 36.

Could you please let me know which example from the Cookbook you’re referring to and we’ll make the change.

Regards,
Mark

Hey Mark,

It was the Swift code example in Feature 16, Feature-a-day series:

https://backendless.com/feature-16-data-retrieval-api-how-to-load-objects-from-an-mbaas-storage/

Thanks

Hi Jay,

The articles were originally written for Swift 1.0, which allowed avoiding cast. Here’s updated code for that example (it shows that cast is required): https://github.com/Backendless/BlogFeatureDay-iOS/blob/master/F16RetrievingData/F16RetrievingDataSwift/ViewController.swift

We’ll update the code snippets in the blog as well.

Regards,
Mark