0

I am new to Node.js and back-end development generally. I've already set up my server and mongoDB and connected them with my iOS app, so basically I have a userSchema and a postSchema in Node.js, a corresponding User and Post class in Objective-c. How can I initialise these two classes with the attributes I set up in Node.js?

Here is the userSchema:

var UserSchema = new mongoose.Schema({
    username : String,
    password : String
});

and the postSchema:

var postSchema = new mongoose.Schema({
    name        : String,
    image       : String,
    description : String,
    comments    : [{
        type: mongoose.Schema.Types.ObjectId,
        ref: "Comment"
    }],
    author      : {
        id : {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User"
        },
        username: String
    }
});

In Xcode, I initialize the Post class like this (don't know if this is correct...but it's working):

@implementation Post

- (id)initWithDictionary:(NSDictionary *)dic
{
    self = [super init];
    if (self)
    {
        super.objectId = [dic objectForKey:@"_id"];
        _name          = [dic objectForKey:@"name"];
        _imgURL        = [dic objectForKey:@"image"];
        _caption       = [dic objectForKey:@"description"];
        _comments      = [dic objectForKey:@"comments"];
        _author        = [dic objectForKey:@"author"];
    }
    return self;
}

@end

In ViewController:

static NSString * const kMyAppBaseURLString = @"http://localhost:4000/";

@interface PostDetailViewController ()

@end

@implementation PostDetailViewController

- (void)loadData
{
    NSURL* url = [NSURL URLWithString:[kMyAppBaseURLString
       stringByAppendingPathComponent:[NSString stringWithFormat:@"posts/%@", postId]]];

    //HTTP GET Request
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"GET";
    [request addValue:@"posts/json" forHTTPHeaderField:@"Accept"];

    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config];

    NSURLSessionDataTask* dataTask = [session dataTaskWithRequest:request
                                            completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
        if (error == nil)
        {
            post = [[Post alloc]initWithDictionary:[NSJSONSerialization JSONObjectWithData:data options:0 error:NULL]];
            [self.tableView reloadData];
        }
    }];

    [dataTask resume];
}

I want to access the user's username by just post.author.username. How do I initialize the User class? Also, am I using the correct way to create the Post class? I am quite new to server side programming. :)

BaseZen
  • 8,650
  • 3
  • 35
  • 47
Dovahkiin
  • 1,239
  • 11
  • 23

1 Answers1

1

JSON objects nest in the natural manner. _author needs to be constructed recursively, not assigned to the unparsed JSON dictionary. So it should be a typed, stored property (as User *) in the definition of Post, and would be built exactly like you built the Post object itself:

_author = [[User alloc] initWithDictionary: [dic objectForKey: @"author"]];

And of course you have to write the User class similarly to Post, with an explicit parsing constructor.

While I'm looking at your code, please see this important issue about respecting the main thread for UI manipulation. Data tasks do not execute their callbacks on [NSOperationQueue mainQueue].

Swift performSegueWithIdentifier not working

Community
  • 1
  • 1
BaseZen
  • 8,650
  • 3
  • 35
  • 47
  • Thank you for your reply. Your solution works perfectly, and makes my question looks indeed a bit silly...I do need more practice on the basic principles of programming. Thanks a lot! – Dovahkiin Aug 24 '16 at 16:36
  • Think nothing of it. Well posed question and well above the truly silly posts. – BaseZen Aug 24 '16 at 16:40