Search code examples
iosobjective-cafnetworkingrealm

Should you asynchronously store images in Realm iOS?


I am currently using Realm for data persistence within an app I am creating.

What I am trying to do is that when the app is first opened, it fetches data from an api. I want to get all the content from that data fetched and store it so the app can be used even if there is no active internet connection.

I can however achieve storing strings like username and mobile number but I am not sure how to store images.

This is what I have so far:

@interface User : RLMObject

@property NSString *userName;
@property NSString *mobileNumber;
@property NSData *avatarData;

@end


- (void)viewDidLoad {
    [super viewDidLoad];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:[NSString stringWithFormat:@"%@users?auth_token=%@",BASE_URL,AUTHENTICATION_TOKEN]parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

        [self storeFetchedData: responseObject];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    }];

}

- (void)storeFetchedData:(NSDictionary *)list {
    RLMRealm *realm = [RLMRealm defaultRealm];
    [realm beginWriteTransaction];

    for (id slUser in list) {
        User *user = [[User alloc] init];
        user.userName = slUser[@"name"];
        user.realName = slUser[@"mobileNumber"];

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){

            user.avatarData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString:slUser[@"image_url"]]];

        });
    }

    [realm commitWriteTransaction];

}

[self.tableView reloadData];

I am not new to iOS but this is my first time using realm or such However, I suspect thread problems as the commit is done on the main thread. I am also curious to know if this is bad practice.

Cheers


Solution

  • While you can store images in Realm as NSData properties, I would recommend writing images out to disk, or using something like Pinterest's PINCache, and storing the path/key in Realm as a string property.