How do I set basic authentication with RestKit 0.20.0? - restkit

I'm trying to use RestKit to call an endpoint that requires basic authentication.
RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[JSNCategory class]];
[mapping addAttributeMappingsFromDictionary:#{
#"id": #"catId",
#"name": #"name"
}];
NSIndexSet *statusCodes = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful);
RKResponseDescriptor *responseDescriptor
= [RKResponseDescriptor responseDescriptorWithMapping:mapping
pathPattern:#"/api/v1/categories"
keyPath:nil
statusCodes:statusCodes];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL
URLWithString:#"https://rest.example.com"]];
RKObjectRequestOperation *operation
= [[RKObjectRequestOperation alloc] initWithRequest:request
responseDescriptors:#[responseDescriptor]];
[operation setCompletionBlockWithSuccess:
^(RKObjectRequestOperation *operation, RKMappingResult *result) {
JSNCategory *cat = [result firstObject];
NSLog(#"Mapped the category: %#", cat);
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSLog(#"Failed with error: %#", [error localizedDescription]);
}];

Using the objectmanager this would be something like:
NSURL* url = [[NSURL alloc]initWithString:#"http://rest.url.com"];
RKObjectManager* objectManager = [RKObjectManager managerWithBaseURL:url];
[objectManager.HTTPClient setAuthorizationHeaderWithUsername:#"username" password:#"password"];
Then, after setting the correct request/response you can use the objectmanager to do a get/post/etc:
[objectManager getObjectsAtPath:endpoint parameters:parameters success:
^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
// do something
}
failure:^(RKObjectRequestOperation *operation, NSError *error) {
// do something
}
];

Related

how to locally store data from WebService in ios 9 using swift

I am using AlamoFire webService in our project, then if connect Internet automatically store webservice data to Local storage data, check the internet connection if true then connect webservice otherwise show local storage data in our app
Objective-C code:
NSUserDefault or CoreData used to locally stored the data from WebService. i have create the custom class NSUserDefault,
(void)HomeScreenGetvalue: (NSArray *)value : (NSString *)key {
[[NSUserDefaults standardUserDefaults] setObject:value forKey:key];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(#"logggg %#",value);
}
(NSArray *)HomeScreenSetvalue: (NSString *)key {
NSArray *savedValue = [[NSUserDefaults standardUserDefaults]
arrayForKey:key];
NSLog(#"savevale %#",savedValue);
return savedValue;
}
Then I have used the NSUserDefault in WebService using AFNetWorking 2.4,
LocalUserDefaults *userDe = [[LocalUserDefaults alloc]init];
if (![self connected]) {
movies = [userDe HomeScreenSetvalue:#"homekeyvalues"].mutableCopy;
[_mytableView reloadData];
} else {
NSURL *url = [NSURL URLWithString:#"http://////?"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//movies are NSMutableArray value
movies = [responseObject objectForKey:#"enquiry"];
NSSortDescriptor *titleSort = [[NSSortDescriptor alloc] initWithKey:#"FirstName"
ascending:YES selector:#selector(caseInsensitiveCompare:)];
movies=[NSMutableArray arrayWithArray:[movies sortedArrayUsingDescriptors:#[titleSort]]];
NSLog(#"The Array: %#",movies);
**[userDe HomeScreenGetvalue:movies :#"homekeyvalues"];**
[self.mytableView reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Request Failed: %#, %#", error, error.userInfo);
}];
[operation start];
}
Its Working for me.......

Can I use RestKit and Realm.io?

I want to use RestKit, but I already use Realm.io instead of CoreData.
Is it possible to use RestKit on top of Realm.io?
Sure you can. Once you get the object back from RestKit:
// GET a single Article from /articles/1234.json and map it into an object
// JSON looks like {"article": {"title": "My Article", "author": "Blake", "body": "Very cool!!"}}
RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[Article class]];
[mapping addAttributeMappingsFromArray:#[#"title", #"author", #"body"]];
NSIndexSet *statusCodes = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful); // Anything in 2xx
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:mapping method:RKRequestMethodAny pathPattern:#"/articles/:articleID" keyPath:#"article" statusCodes:statusCodes];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://restkit.org/articles/1234.json"]];
RKObjectRequestOperation *operation = [[RKObjectRequestOperation alloc] initWithRequest:request responseDescriptors:#[responseDescriptor]];
[operation setCompletionBlockWithSuccess:^(RKObjectRequestOperation *operation, RKMappingResult *result) {
Article *article = [result firstObject];
// I would put the Realm write here
NSLog(#"Mapped the article: %#", article);
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSLog(#"Failed with error: %#", [error localizedDescription]);
}];
[operation start];
You will need to do two things:
Create your RealmArticle model (in this case) that inherits from RLMObject
Then you will just need to write to your realm
RLMRealm *realm = [RLMRealm defaultRealm];
[realm beginWriteTransaction];
[RealmArticle createInDefaultRealmWithObject:article];
[realm commitWriteTransaction];

Send email from iOS app using SendGrid

I am trying to to use mail api from sendgrid.com but everytime it finishes with failure block.
Also I don't understand how to send the image as an attachment in the email. Can anybody tell me whats wrong in below code & how can I send image ? I am using below code for now
-(void)sendEmail
{
NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
[params setValue:#"username" forKey:#"api_user"];
[params setValue:#"sdsfddf23423" forKey:#"api_key"];
[params setValue:#"test#gmail.com" forKey:#"to"];
[params setValue:#"test user" forKey:#"toname"];
[params setValue:#"Test SendGrid" forKey:#"subject"];
[params setValue:#"Test SendGrid from iOS app" forKey:#"text"];
[params setValue:#"noreply#gmail.com" forKey:#"from"];
NSURL *url = [NSURL URLWithString:#"https://sendgrid.com/api"];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL: url];
NSMutableURLRequest *request = [client requestWithMethod:POST path:#"/mail.send.json" parameters:params];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
DLog(#"Get latest product info response : %#", response);
NSLog(#"Success");
} failure: ^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure");
}];
[operation start];
}
Thanks in advance.
Update
I made some changes in code & now I can send the email successfully as below
-(void)sendEmailWithoutImage
{
NSDictionary *parameters = #{#"api_user": #"username",
#"api_key": #"sdsfddf23423",
#"subject":#"Test SendGrid",
#"from":#"noreply#gmail.com",
#"to":#"test#gmail.com",
#"text":#"Test SendGrid from iOS app"};
[[MyAPIClient sharedAPIClient] POST:#"mail.send.json" parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject)
{
NSLog(#"Success::responseObject : %#", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"Error::Mail response : %#", error);
}];
}
But when I try to send the image as attachment then it result in 400 bad request. So I think there is some error in my file uploading block. Here is my code
-(void)sendEmailWithImage
{
NSDictionary *parameters = #{#"api_user": #"username",
#"api_key": #"sdsfddf23423",
#"subject":#"Test SendGrid",
#"from":#"noreply#gmail.com",
#"to":#"test#gmail.com",
#"text":#"Test SendGrid from iOS app"};
[[MyAPIClient sharedAPIClient] POST:#"mail.send.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
UIImage *image = [UIImage imageNamed:#"redWine.png"];
NSData *imageToUpload = UIImagePNGRepresentation(image);
[formData appendPartWithFileData:imageToUpload name:#"files" fileName:[NSString stringWithFormat:#"%#",#"abc.png"] mimeType:#"image/png"];
}
success:^(NSURLSessionDataTask *task, id responseObject)
{
NSLog(#"Success::responseObject : %#", responseObject);
}
failure:^(NSURLSessionDataTask *task, NSError *error)
{
NSLog(#"Error::Mail response : %#", error);
}];
}
Can you anybody tell me whats going wrong while uploading the image ?
Thanks
Just modified your code a little. It looks like there was an issue with the parameters being sent and the URL path.
Also since you are already using AFNetworking to make your POST request, you can follow their docs and example on how to send a photo over here: http://cocoadocs.org/docsets/AFNetworking/2.0.1/
NSDictionary *parameters = #{#"api_user": #"username",
#"api_key": #"sdsfddf23423",
#"Test SendGrid":#"test",
#"from":#"noreply#gmail.com",
#"to":#"test#gmail.com",
#"text":#"Test SendGrid from iOS app"};
NSURL *url = [NSURL URLWithString:#"https://sendgrid.com/api/"];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL: url];
NSMutableURLRequest *request = [client requestWithMethod:#"POST" path:#"mail.send.json" parameters:parameters];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
// DLog(#"Get latest product info response : %#", response);
NSLog(#"Success: %#", response);
} failure: ^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"%#",error);
}];
[operation start];
Update**
Created a Sendgrid-ios library to make it easier to send an email and photo attachment.
//create Email Object
gridmail *msg = [gridmail user:#"username" andPass:#"password"];
//set parameters
msg.to = #"foo#bar.com";
msg.subject = #"subject goes here";
msg.from = #"me#bar.com";
msg.text = #"hello world";
msg.html = #"<h1>hello world!</h1>";
//Image attachment
[msg attachImage:self.photo];
//Send email through Web API Transport
[msg sendWithWeb];

How to perform a DELETE request using RestKit (0.20)?

I'm trying to send a DELETE request using RestKit, but it seems that it is always sent as "GET". Here is my code:
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor
responseDescriptorWithMapping:[self objectMapping]
method:RKRequestMethodDELETE
pathPattern:nil
keyPath:nil
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
RKObjectRequestOperation *objectRequestOperation = [[RKObjectRequestOperation alloc] initWithRequest:request responseDescriptors:#[ responseDescriptor ]];
[objectRequestOperation setCompletionBlockWithSuccess:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
[delegate onRequestSuccess:mappingResult.array];
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
RKLogError(#"operation failed with error: %#", error);
[delegate onRequestError:operation message:error];
}];
[objectRequestOperation start];
I tried also using RKObjectManager:deleteObject, which does correctly send a DELETE request, but the response does not get mapped.
RKObjectManager *manager = [RKObjectManager managerWithBaseURL:request.url];
[manager addResponseDescriptor:responseDescriptor];
[manager deleteObject:nil path:request.urlString parameters:nil
success:^(RKObjectRequestOperation *operation , RKMappingResult *mappingResult) {
Tag *tag = mappingResult.firstObject; // this is null, does not get mapped
} failure:^(RKObjectRequestOperation *operation , NSError *error) {
RKLogError(#"Error deleting tag %#, error: %#", tagId, error);
}];
If you're using RKObjectRequestOperation you need to configure the request yourself. It's GET because that is the default.
If you use RKObjectManager then you can use deleteObject instead which will do it for you.

Access Response Data in Success callback

Is there any way to access the response data in the success block for a request using the object manager?
[objectManager postObject:[User class] path:#"/users" parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
NSLog(#"success");
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSLog(#"failure");
}];
It seems like there should be some way to use the mapping or operation to get this information as maybe NSData or something.
You can get this info from the RKObjectRequestOperation *operation
operation.HTTPRequestOperation.response
operation.HTTPRequestOperation.responseData
operation.HTTPRequestOperation.responseString
try this
[objectRequestOperation setCompletionBlockWithSuccess:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
// parse the response---
NSDictionary *myDic = [NSJSONSerialization JSONObjectWithData:operation.HTTPRequestOperation.responseData options:NSJSONReadingMutableLeaves error:nil];
NSLog(#"=======:%#",myDic);
NSLog(#"MY email============ %# ",[myDic objectForKey:#"Email"]);
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
RKLogError(#"Operation failed with error: %#", error);
}];

Resources