1

i am working on a way to parse json from the web in my app.

Source: http://api.randomuser.me/

My Code:

var bytes: NSMutableData?

@IBAction func loadJson(sender: AnyObject) {

    let request = NSURLRequest(URL: NSURL(string: "http://api.randomuser.me/")!)

    let loader = NSURLConnection(request: request, delegate: self, startImmediately: true)

}

func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {

        self.bytes = NSMutableData()

}

func connection(connection: NSURLConnection!, didReceiveData conData: NSData!) {

        self.bytes?.appendData(conData)

}

func connectionDidFinishLoading(connection: NSURLConnection!) {

    let jsonResult: Dictionary = NSJSONSerialization.JSONObjectWithData(self.bytes!, options: NSJSONReadingOptions.MutableContainers, error: nil) as! Dictionary<String, AnyObject>

    let results: NSArray = jsonResult["results"]! as! NSArray

    println(results)

    for result in results {

        // Works
        println(result)

        // Works
        println(result["seed"])

        // Does not work !!! why?
        println(result["user"]["email"])

    }

}

Why can't I get the email from the array?

If you want you can take a look at the json in the link above.

1
  • Rather than linking to the JSON, please include it directly in the question. I deleted the opinion-based part of your question in the interest of keeping your question on-topic. But ultimately, this question is still borderline. Can you elaborate on // Does not work !!! why? What does "does not work" mean? Commented Jul 19, 2015 at 13:37

1 Answer 1

1

By using SwiftyJSON you can handle your JSON data easily this way:

@IBAction func loadJson(sender: AnyObject) {

    let baseURL = NSURL(string: "http://api.randomuser.me/")
    let userData = NSData(contentsOfURL: baseURL!)

    let json = JSON(data: userData!)
    let seeds = json["results"][0]["seed"].stringValue
    let email = json["results"][0]["user"]["email"].stringValue
    println(seeds)    //1bbefb89fc47c81501
    println(email)    //[email protected]
}

Hope this will help.

Sign up to request clarification or add additional context in comments.

5 Comments

thanks this lib is great, but how to deal with basic authentification on the web server?
i mean, if there is username and a password required for access*
you can save username and password with this and you can use it.
oh sorry, i meant: if i request the web server to load json, but the webserver requires username and password for authentification. you know what i mean?
Yes I understand now but I have no Idea about it.Feel free to ask another question with your issue..:)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.