Search code examples
jsonswiftalamofire

Swift: How to Read JSON Data from JSON Data


I have read some data from JSON, which include a url of another JSON file, I need to read that JSON file and store them as well. I don't know where should I add the second process of reading JSON. I am very new to swift, anyone can give me some suggestions? thanks so much.

var posts: [Posts] = [Posts]()

@IBOutlet weak var theCollectionView: UICollectionView!
func getCategories(){

    Alamofire.request(.GET, "http://localhost:8888/wordpress/wp-json/wp/v2/categories").responseJSON { (response) in
        if let jsonFile = response.result.value {

            var arrayOfPosts = [Posts]()

            for post in jsonFile as! NSArray {

                let postObj = Posts()

               // if !(post.valueForKeyPath("featured_image_thumbnail_url") is NSNull){

                  //  postObj.postThumbnailUrlString = post.valueForKeyPath("featured_image_thumbnail_url") as! String
                    postObj.postCategoryCode = "\(post.valueForKeyPath("id") as! NSNumber)"
                    postObj.theDictionary = post.valueForKeyPath("_links") as! NSDictionary
                    postObj.theCategoryArray = (postObj.theDictionary.valueForKeyPath("wp:post_type") as? NSArray)!
                    postObj.postCategoryListUrl = postObj.theCategoryArray[0].valueForKeyPath("href") as! String

                    arrayOfPosts.append(postObj)



            }

            self.posts = arrayOfPosts
            self.theCollectionView.reloadData()


            }
        }
}

class Posts: NSObject{

var postTite:String = ""
var postContent: String = ""
var postCategoryCode: String = ""
var postThumbnailUrlString: String = ""
var theCategoryArray = NSArray()
var theDictionary = NSDictionary()
var postCategoryListUrl: String = ""  
}

I am using Alamofire, I tried add another loop after I got "postObj.postCategoryListUrl", but it didn't work. I need to use the url of "postObj.postCategoryListUrl" to read data of "postTitle", "postThumbnailUrlString" and "postContent". I am very new to swift, need some suggestions about this, thanks so much.


Solution

  • You can do Alamife.request for second json after this line

    self.posts = arrayOfPosts
    

    and when the second json data purse will complete then use this line.Then you will have complete post and post details.

    dispatch_async(dispatch_get_main_queue(),{
         self.theCollectionView.reloadData()
     })