Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON to NSMutableArray (Swift in Xcode)

Tags:

json

ios

I've been working on an app to utilize google's YouTube API. I had this app fully functioning in Objective-C, but I've ran into some problems in Swift.

This is what is looks like in Objective-C,

  -(void) retrieveData {

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //Change this link in order to get the data you want Change the Username!!!
    [manager GET:[NSString stringWithFormat:@"https://gdata.youtube.com/feeds/api/users/%@/uploads?v=2&alt=jsonc", _YoutuberName] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //Parsing the JSON into something readable
        self.posts = (NSDictionary *)responseObject;
        self.post = self.posts[@"data"][@"items"];

        title = [[self.post valueForKeyPath:@"title"]count];
        // Reloading the Data in the Table
        [self.tableView reloadData];
        [self.refreshControl endRefreshing];

        NSLog(@"%@", self.post);

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];

This is what I have so far in Swift,

 var posts = NSDictionary()
var post = NSMutableArray()


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    var manager = AFHTTPRequestOperationManager()

    manager.GET("https://gdata.youtube.com/feeds/api/users/archetapp/uploads?v=2&alt=jsonc", parameters: nil, success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in

        self.posts = NSDictionary(objects: [responseObject], forKeys: ["data"])
        NSLog("\(self.posts)")



        }, failure: { (operation: AFHTTPRequestOperation!,error: NSError!) in
        println("Error: " + error.localizedDescription)

        })

}

and it prints this... (This is exactly the same as the Objective-C, but Obj-C starts at where it says "items")

   data =     {
    apiVersion = "2.1";
    data =         {
        items =             (
                            {
                accessControl =                     {
                    autoPlay = allowed;
                    comment = allowed;
                    commentVote = allowed;
                    embed = allowed;
                    list = allowed;
                    rate = allowed;
                    syndicate = allowed;
                    videoRespond = moderated;
                };
                aspectRatio = widescreen;
                category = Education;
                commentCount = 10;
                content =                     {
                    1 = "rtsp://r4---sn-a5m7zu7s.c.youtube.com/CigLENy73wIaHwl-BISTGI_oVhMYDSANFEgGUgx1c2VyX3VwbG9hZHMM/0/0/0/video.3gp";
                    5 = "https://www.youtube.com/v/VuiPGJOEBH4?version=3&f=user_uploads&app=youtube_gdata";
                    6 = "rtsp://r4---sn-a5m7zu7s.c.youtube.com/CigLENy73wIaHwl-BISTGI_oVhMYESARFEgGUgx1c2VyX3VwbG9hZHMM/0/0/0/video.3gp";
                };
                description = "Have an awesome day! #DFTBA\n\nSupport me on Patreon : Patreon.com/archetapp\n\nSubscribe to my channel! - http://www.youtube.com/archetapp\n\nCheck out my Website! - http://www.archetapp.com\nCheck me out on Twitter - http://www.twitter.com/archetapp";
                duration = 437;
                favoriteCount = 0;
                id = VuiPGJOEBH4;
                likeCount = 21;
                player =                     {
                    default = "https://www.youtube.com/watch?v=VuiPGJOEBH4&feature=youtube_gdata_player";
                    mobile = "https://m.youtube.com/details?v=VuiPGJOEBH4";
                };

etc......

I know I have to get down to the items, so my main question is how to do exactly as I did in Objective-C where I did self.posts[@"data"][@"items"]; as this doubling of brackets is not allowed in Swift.

Any help would be a appreciated! Thanks! :)

If you want to download my original product done in Objective-C, to get an idea of what i'm trying to accomplish, you can check it out - here

like image 790
Jared Davidson Avatar asked Nov 23 '25 04:11

Jared Davidson


2 Answers

You can get list or item form you self.posts dictionary.

manager.GET("https://gdata.youtube.com/feeds/api/users/archetapp/uploads?v=2&alt=jsonc", parameters: nil, success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in

    self.posts = NSDictionary(objects: [responseObject], forKeys: ["data"])
        NSLog("\(self.posts)")
        let itemArray : NSMutableArray = self.posts.objectForKey("items") as! NSMutableArray
         NSLog("\(itemArray)")
    },
    failure: { (operation: AFHTTPRequestOperation!,error: NSError!) in
        println("Error: " + error.localizedDescription)
    })
}

Hope that helps you,

Enjoy Coding !!

like image 181
Viral Savaj Avatar answered Nov 24 '25 20:11

Viral Savaj


Just add this after getting data to posts:

let yourItems : NSMutableArray = self.posts.objectForKey("items") as! NSMutableArray

this is same as this:

self.post = self.posts[@"data"][@"items"];

self.post should be an NSMutableArray. Please change the type.

Hope this helps... :)

like image 34
Rashad Avatar answered Nov 24 '25 19:11

Rashad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!