0

I have a json file

I need to get the latest "id": "article" "createdAt": "2016-04-22T03:38:39.130Z" date. How do I go about getting this data from the request in swift?

Note: Sorry im a swift newb.

1
  • should try SwiftyJSON Commented Apr 22, 2016 at 6:46

2 Answers 2

2
let url = "https://cdn.contentful.com/spaces/maz0qqmvcx21/entries?access_token=ae8163cb8390af28cd3d7e28aba405bac8284f9fe4375a605782170aef2b0b48";
var jsonData:NSData?

do{
    jsonData = try NSData(contentsOfURL: NSURL(string: url)!, options: NSDataReadingOptions.DataReadingUncached)
    let jsonObject:AnyObject? = try NSJSONSerialization.JSONObjectWithData(jsonData!, options: NSJSONReadingOptions.AllowFragments)
    if let itemArray = jsonObject?.objectForKey("items") as? NSArray{
        for item in itemArray{
            if let sysItem = item.objectForKey("sys"){
                //this is createdAt
                if let createdAt = sysItem.objectForKey("createdAt") as? String{
                    print("createdAt:\(createdAt)")
                }

                if let contentTypeItem = sysItem.objectForKey("contentType")!.objectForKey("sys"){
                    //this is id
                    if let id = contentTypeItem.objectForKey("id") as? String{
                        print("id:\(id)")
                    }
                }
            }
        }
    }
}catch let err as NSError{
    print("err:\(err)")
}

This code dosen't use any libraries,but you can use SwiftyJSON,this is will be easy to parse json.

Hope this help.

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

1 Comment

Thanks! Solved my problem :).
1

This can be done in simple way. I am assuming that you have parsed your json to dictionary

You have a key with items which is an array of dictionary and inside that dictionary you have createdAt and id(well it is deeper into the hierarchy but I will show you how to get it) keys. You can access it by simply doing this.

for dict in jsonDict["items"] as! Array<NSDictionary> {
    let sysDict = dict["sys"] as! NSDictionary
    print(sysDict["createdAt"]) //prints all createdAt in the array
    let contentDict = sysDict["contentType"]
    print((contentDict["sys"] as! NSDictionary)["id"]) // prints all ids
}

Hope this helps.

Comments

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.