-
Notifications
You must be signed in to change notification settings - Fork 0
Attach a File to an RKObjectLoader
Imagine that we have a Contact object that contains an NSImage property like so:
@interface Contact : NSObject
@property (nonatomic, retain) NSString* name;
@property (nonatomic, retain) NSString* address;
@property (nonatomic, retain) UIImage* avatarImage;
// Return avatarImage as a NSData representation
- (NSData*)avatarImageData;
@end
We want to be able to submit that image to our remote server for processing. Currently RestKit only supports Form URL Encoded and JSON as serialization formats out of the box. Images and files can be uploaded by leveraging the RKParams
class to construct a multi-part form encoded document. By combining the functionality of RKParams
with the serialization capabilities of RKObjectSerializer
, we can serialize our object into a dictionary and then attach the avatar image and submit it for processing:
[[RKObjectManager sharedManager] postObject:contact delegate:self block:^(RKObjectLoader* loader) {
RKObjectMapping* serializationMapping = [[[RKObjectManager sharedManager] mappingProvider] serializationMappingForClass:[Contact class]];
NSError* error = nil;
NSDictionary* dictionary = [[RKObjectSerializer serializerWithObject:contact mapping:serializationMapping] serializedObject:&error];
RKParams* params = [RKParams paramsWithDictionary:dictionary];
[params setData:[contact avatarImageData] MIMEType:@"image/png" forParam:@"avatar_image"];
loader.params = params;
}];
The object serializer will convert our local object into an NSDictionary representation for us, which can then be loaded into an RKParams instance. From here we can attach the image to the document and assign it to object loader before it is sent to the server for processing.