Accessing Strings in JSON Response

Hi,
I am new to iOS programming using Swift. I am having a difficult time accessing the strings inside the JSON responses. I want to first use SwiftyJSON to unwrap the object and then access the strings after, but in the console the SwiftyJSON responses display null. The normal print statement prints the JSON names to the console as expected. Please feel free to review my code below:


import Foundation
protocol WeatherServiceDelegate{
 func setWeather(weather: Weather)
 
}
class WeatherService {
 //backendless stuff
 var backendless = Backendless.sharedInstance()
 var results: [coffee_details]! = []
 
 
 
 
 var delegate: WeatherServiceDelegate?
 
 func getWeather(city: String){
 //request weather data
 //wait...
 //process data
 
 print("Weather Service city: \(city)")
 
 let weather = Weather(cityName: city, temp: 333.33, description: "A bright day")
 
 
 
 
 let startTime = NSDate()
 
 backendless.persistenceService.of(coffee_details.ofClass()).find(
 BackendlessDataQuery(), response: { (results: BackendlessCollection!) -> () in
 let currentPage = results.getCurrentPage()
 
 
 //self.tableView.reloadData()
 //prints to console
 print("Loaded \(currentPage.count) results objects")
 print("Total results in the Backendless storage - \(results.totalObjects)")
 
 
 for result in currentPage {
 
 print("Results = \(result.name)")
 let json = JSON(result)
 let tempName = json["name"]
 
 print("test \(tempName) ")
 
 }
 
 print("Total time (ms) - \(1000*NSDate().timeIntervalSinceDate(startTime))")
 }
 ,
 
 error: { (fault : Fault!) -> () in
 print("Server reported an error: \(fault)")
 })
 
 
 
 
 
 
 if delegate != nil{
 delegate?.setWeather(weather)
 }
 
 
 }
}

Here is what I am getting in my Console:


Optional("test")
Weather Service city: test
Loaded 53 results objects
Total results in the Backendless storage - 53
Results = The Perfect Scoop & Boba Tea
test null 
Results = Cafe Gelato
test null 
Results = Strip View Cafe
test null 
Results = Jackie Bee Boba Express
test null 
Results = Caffe Bottega
test null 
Results = Aromas Teas & Coffee
test null 
Results = Petrossian Bar
test null 
Results = Baguette Cafe
test null 
Results = Palio
test null 
Results = Greenwich Village Coffee Co.
test null 
Results = Coffee, Tea, or Me?
test null 
Results = La Belle Terre Bread French Bakery Cafe
test null 
Results = Real Donuts #1
test null 
Results = Pour
test null 
Results = Crown Bakery
test null 
Results = Bambu
test null 
Results = Coffee Pub
test null 
Results = Pawn Donut and Coffee
test null 
Results = Chewy Boba Company
test null 
Results = PublicUs
test null 
Results = Paris Baguette
test null 
Results = Tea Time Cafe
test null 
Results = Easy Life Boba Tea
test null 
Results = Wake Up Coffee Cafe
test null 
Results = Leone Cafe
test null 
Results = MadHouse Coffee
test null 
Results = Avery's Coffee Roasters
test null 
Results = Cafe Teaze
test null 
Results = No 1 Boba Tea
test null 
Results = No 1 Boba Tea
test null 
Results = No 1 Boba Tea
test null 
Results = The Beat Coffeehouse
test null 
Results = Jean Phillippe Patisserie
test null 
Results = Jean Phillippe Patisserie
test null 
Results = Cafe Darak
test null 
Results = Tiabi Coffee & Waffle
test null 
Results = Grouchy Johns Coffee
test null 
Results = Makers & Finders Coffee
test null 
Results = Kung Fu Tea
test null 
Results = Sunrise Coffee
test null 
Results = Desert Wind Coffee Roasters
test null 
Results = IS SWEET
test null 
Results = Dutch Bros. Coffee
test null 
Results = The Lodge Coffee House & Tavern
test null 
Results = The Cuppa Coffee Bar
test null 
Results = Tipsy Coffee House
test null 
Results = Holley's Cuppa
test null 
Results = Ice Monster Cafe
test null 
Results = Illumilatte Brew Society
test null 
Results = Sambalatte Torrefazione
test null 
Results = Sambalatte Torrefazione
test null 
Results = Sambalatte Torrefazione
test null 
Results = Serenade
test null 
Total time (ms) - 840.1820063591


I fear this is a trivial fix, but I have spent too much time with no luck. May someone please have a look?
Thank you,

I thought you’d be retrieving your weather objects, but then you get coffee_details? That looked very odd

backendless.persistenceService.of(coffee_details.ofClass()).find(

There is no JSON with Backendless. The response will contain objects of the data type you specified in the of() method when you did backendless.persistenceService.of(). So if you retrieve your coffee_details, the response will contain a collection of coffee_details objects from the “coffee_details” data table. No additional conversion is needed - just use the objects you get back from the server.

Here’s a specific example:
https://backendless.com/feature-16-data-retrieval-api-how-to-load-objects-from-an-mbaas-storage/

Mark

That’s what my initial thought process was heading towards but then it came time to use my responses as strings and then set those strings into UILabels outlets. I ran into some problems there, but I am refreshing my understanding of Swift to see if I missed anything. That’s why I was using a tutorial weather app from YouTube with my current Backendless data.

Is it working for you now?

No, I completely removed references to SwiftyJSON & am directly accessing my values now but I am receiving the following error when attempting to set my response strings to UILabel text. This is displayed in the storyboard:

.../Main.storyboard: The locationNameLabel outlet from the Search to the UILabel is invalid. Outlets cannot be connected to repeating content.

This is what my tableView function looks like:









    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("ResultCell") as! ResultCell

        let row = indexPath.row

        //let result = results[indexPath.row] as! [String: AnyObject]

        //let resultOB = results[row] as NSObject

        let startTime = NSDate()

        //let result: AnyObject = result["name"] as! NSObject

        backendless.initApp(APP_ID, secret:SECRET_KEY, version:VERSION_NUM)




        

        

        //cell.textLabel!.text = result["results"] as String

        //resultDisplayName.text = result["results"] as String




        //self.resultDisplayName.text = locationName!.localizedUppercaseString

        

        

        //setLocationName(locationService)

        

        backendless.persistenceService.of(coffee_details.ofClass()).find(

            BackendlessDataQuery(), response: { (results: BackendlessCollection!) -> () in

                let currentPage = results.getCurrentPage()

                

                //self.tableView.reloadData()

                //prints to console

                print("Loaded \(currentPage.count) results objects")

                print("Total results in the Backendless storage - \(results.totalObjects)")

                

                

                for result in currentPage {

                    

                    print("Results = \(result.name)")

                    //self.resultDispName.text = result.name as! String

                    

                    

                    

                    if let locationLabel = result.name {

                        self.locationNameLabel.text = result.name

                        

                    }

                    

                    

                }

                

                print("Total time (ms) - \(1000*NSDate().timeIntervalSinceDate(startTime))")

            }

            ,

            

            error: { (fault : Fault!) -> () in

                print("Server reported an error: \(fault)")

        })

        

        







        return cell

    }

The stuff I commented out are stuff I tried.

It looks like the error you’re getting refers to your code rather than Backendless API. If you comment out the following, do you get all the names in the log?

if let locationLabel = result.name {
self.locationNameLabel.text = result.name
}

If I comment the said code out, I still get the Storyboard error for repeating content.

If I remove the Storyboard label outlet reference, the code runs but I do not get any responses in the console.

This tells me that the error is not with the Backendless API, but with other parts of the project.

I now realize my issue is out of the scope of this support forum.

Thank you for alleviating my confusion, Mark.