Forming Multi-part request through RestKit - objective-c

This is my code to post multi-part data to server. What i observe is there is only image data being included in request, not the article object. Please let me know if someone has done this stuff successfully in the past. Thanks in advance.
RKObjectMapping *requestMapping = [RKObjectMapping requestMapping];
[requestMapping addAttributeMappingsFromArray:#[#"title", #"author", #"body"]];
RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:requestMapping
objectClass:[Article class] rootKeyPath:#"article" method:RKRequestMethodAny];
[manager addRequestDescriptor:requestDescriptor];
Article *article = [Article new];
article.title = #"Introduction to RestKit";
article.body = #"This is some text.";
article.author = #"Blake";
NSMutableURLRequest *request = [objectManager multipartFormRequestWithObject:article
method:RKRequestMethodPOST
path:path
parameters:nil
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData
name:imageInfo
fileName:imageName
mimeType:#"image/jpeg"];
}];
RKObjectRequestOperation *operation1 = [objectManager objectRequestOperationWithRequest:request
success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult)
{
// Process data
NSLog(#"success");
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
// An error occurred
NSLog(#"error");
}];

Resolved this using appendPartWithHeaders. Source.
Lemme know if someone needs to see implementation more closely.

Related

RestKit - Response descriptor not added

I use RestKit version 0.26 and try to map a response to core data
This is the code I use for the code I use to built the request and Descriptor:
-(void)getProductListProductWithPageNumber: (int) pageNumber managedObjectStore: (RKManagedObjectStore *)managedObjectStore {
// initialize AFNetworking HTTPClient
NSURL *baseURL = [NSURL URLWithString:#"https://server.com"];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
RKObjectManager *objectManager = [[RKObjectManager alloc] initWithHTTPClient:client];
objectManager.managedObjectStore = managedObjectStore;
RKResponseDescriptor *productListrResponseDescriptor =
[RKResponseDescriptor responseDescriptorWithMapping:[[CategoricalSystemDownloadManager sharedDownloadManager] getCDProductListProductMapping:managedObjectStore]
method:RKRequestMethodGET
pathPattern:#"/PLController/plProducts/:"
keyPath:nil
statusCodes:[NSIndexSet indexSetWithIndex:200]];
[objectManager addResponseDescriptor:productListrResponseDescriptor];
[objectManager getObjectsAtPath:[NSString stringWithFormat:#"/PLController/plProducts/currentResponseBody-%d", pageNumber]
parameters:nil
success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
}
failure:^(RKObjectRequestOperation *operation, NSError *error) {
}];
}
The mapped JSON does is an array -> key path nil, right?
It looks like this:
[
{
"productId": 240,
"brandId": 69
}
]
This is the error
which failed to match all (0) response descriptors
I messed up the pathPattern. It should be /PLController/plProducts/:currentResponseBody

AFNetworking 2.5.4 sending file with PATCH request

Using AFNetworking for communication between REST API and my application I ran into a strange behaviour wenn trying to upload an image with PATCH request.
I use following code:
- (void) uploadImage: (UIImage *)image {
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{};
AFHTTPRequestSerializer *requestSerializer = [manager requestSerializer];
NSError *e = nil;
NSMutableURLRequest *request = [requestSerializer multipartFormRequestWithMethod:#"PATCH"
URLString:requestString
parameters:parameters
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:UIImagePNGRepresentation(image)
name:#"image"
fileName:#"image.png"
mimeType:#"image/png"];
} error:&e];
[manager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog("OK");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog("FAILED");
}];
}
Neither success not failed block of operation will be reached.
Wenn I change the request method to POST everything works fine, but the Server accepts only PATCH method for this case.
Am I doing something wrong?
I finally found a solution for my question:
- (void)uploadImage:(UIImage *)image
withSuccess:(SomeSuccessBlock)success
failure:(SomeFailureBlock)failure {
NSString *requestString = "Some url";
NSError *e = nil;
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
AFHTTPRequestSerializer *requestSerializer = [manager requestSerializer];
NSMutableURLRequest *request = [requestSerializer multipartFormRequestWithMethod:#"POST" URLString:requestString parameters:#{}
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:UIImagePNGRepresentation(image)
name:#"user[avatar]"
fileName:#"avatar.png"
mimeType:#"image/png"];
} error:&e];
if (e && failure) {
failure(e);
return;
}
[request setHTTPMethod:#"PATCH"];
[request setValue:#"PATCH" forHTTPHeaderField:#"X-HTTP-Method-Override"];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
if (success) {
success();
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (failure) {
failure(error);
}
}];
[operation start];
}

How to POST a simple object's data to Server using RestKit 0.20

I am new in RestKit. I did not find a proper documentation or tutorial to send simple object data to Restful API.
Here is my problem in detail.
I have a class with name User having two properties for now: email and password.
I want to send them to server using RestKit 0.20.
I found some tutorials but all of them are outdated for RestKit v 0.10. I found this question but this is outdated as well. There is no sharedInstance selector of class RKObjectManager in RestKit 0.20 but sharedManager.
Any help would be great.
Finally I found the solution. Thanks #Mateusz for helping me out.
Here is the solution.
// Construct a request mapping for User
RKObjectMapping *requestMapping = [RKObjectMapping requestMapping];
[requestMapping addAttributeMappingsFromDictionary:#{ #"email": #"email", #"password": #"password" }];
// construct a response mapping for User
RKObjectMapping *responseMapping = [RKObjectMapping mappingForClass:[User class]];
[responseMapping addAttributeMappingsFromDictionary:#{#"email": #"email", #"password": #"password", #"guid": #"guid"}];
RKRequestDescriptor *req = [RKRequestDescriptor requestDescriptorWithMapping:requestMapping objectClass:[User class] rootKeyPath:#"user" method:RKRequestMethodPOST];
RKResponseDescriptor *res = [RKResponseDescriptor responseDescriptorWithMapping:responseMapping method:RKRequestMethodAny pathPattern:nil keyPath:#"user" statusCodes:[NSIndexSet indexSetWithIndex:200]];
// Register our descriptors with a manager
RKObjectManager *manager = [RKObjectManager managerWithBaseURL:[NSURL URLWithString:#"http://localhost/api/user/"]];
[manager addRequestDescriptor:req];
[manager addResponseDescriptor:res];
// preparing sending User object
User *user = [User new];
user.email = #"example#example.com";
user.password = #"password";
NSLog(#"user email : %#", user.email);
[manager postObject:user path:#"user" parameters:#{#"api_key": MY_API_KEY} success:^(RKObjectRequestOperation *operation, RKMappingResult *result) {
NSArray *arr = [result array];
User *temp= [arr objectAtIndex:0];
NSLog(#"SUCCESS ---------------------------- User's email: %#", temp.email);
NSLog(#"User's guid: %#", temp.guid);
// NSLog(#"--------- - --- -- - all resutl: %#", result);
}
failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSLog(#"failed post %#", error);
NSLog(#"%#",operation.description);
NSLog(#"%#",operation.HTTPRequestOperation.description);
}];

Authenticating Users using AfNetworking

I'm trying to authenticate users, but my app keeps on crashing with error 'NSInternalInconsistencyException', reason: 'Invalid parameter not satisfying: urlRequest' what am I doing wrong?
Below is my code
-(IBAction)btnLogin:(id)sender
{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager alloc];
NSDictionary *parameters = #{#"email": email.text, #"pass": pword.text};
NSString *str = #"http://www.blablablabla/api2/user.php?type=login";
str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [manager.requestSerializer requestWithMethod:#"POST" URLString:str parameters:parameters];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
//[operation setCredential:credential];
[operation setResponseSerializer:[AFJSONResponseSerializer alloc]];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure: %#", error);
}];
[manager.operationQueue addOperation:operation];
}
You seem to be alloc-ing the AFHTTPRequestOperationManager but does it ever get init'ed?
Also, check the request for nil before passing it to the AFHTTPRequestOperation.
Checking parameters and alloc'ed/created instances for nil can help you tell IMMEDIATELY where a problem is.
Hope this helps.

What is the simplest way to use multipart/form-data in AFNetworking 2.0? ios7

I need to send all my forms on server, firstly text forms and then images. Do someone working with it?
The documentation page of AFNetworking shows the following example:
Multi-Part Request
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"foo": #"bar"};
NSURL *filePath = [NSURL fileURLWithPath:#"file://path/to/image.png"];
[manager POST:#"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:filePath name:#"image" error:nil];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];