mardi 5 mai 2015

Create API Class to handle JSON Data Swift

I'm extremely new to handling JSON Data in Swift, and almost just as new to Swift. In a Playground I wrote a whole bunch of code that parsed JSON Data out.

However I realized I don't want to copy and paste this code into every view controller that uses only some of the data. I want to create a custom class that handles the json data.

Here is a bit of my code:

var status: String!
var message: String!
var code: Int!
var dataArray: [NSDictionary]!
var responseCode: String!


var url: NSURL!
var session: NSURLSession!



url = NSURL(string: "http://ift.tt/1zyLZhE")

session = NSURLSession.sharedSession()


let task = session.dataTaskWithURL(url!, completionHandler: { data, response, error -> Void in
if (error != nil) {
    // println(error)

} else {
    let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary




    status = jsonResult["status"] as! String
    message = jsonResult["message"] as! String
    code = jsonResult["code"] as! Int
    dataArray = jsonResult["data"] as! [NSDictionary]


}

})
task.resume()

I then attempted to create a class like this:

class JsonClass {

var status: String!
var message: String!
var code: Int!
var dataArray: [NSDictionary]!
var responseCode: String!


var url: NSURL!
var session: NSURLSession!


init() {
 url = NSURL(string: "http://ift.tt/1zyLZhE")

session = NSURLSession.sharedSession()


let task = session.dataTaskWithURL(url!, completionHandler: { data, response, error -> Void in
if (error != nil) {
    // println(error)

} else {
    let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary




    status = jsonResult["status"] as! String
    message = jsonResult["message"] as! String
    code = jsonResult["code"] as! Int
    dataArray = jsonResult["data"] as! [NSDictionary]


}

})
task.resume()


}

I thought that within a new class I would be able to do something like this:

let jsonAPI = JsonClass()
println(jsonAPI.status)
println(jsonAPI.message)

etc...

However, any attempt to access an instance of the JsonClass results in every JsonClass property having a value of nil.

What are my next steps to accessing this data using instances of this class?

Aucun commentaire:

Enregistrer un commentaire