Rest kit VS ASIHTTPRequest - restkit

I am using "RestKit 0.20.3` in my project,
due to some crucial reasons I am going to convert all my API calls to Ret kit,
please can any one tell me how can I make a same call like below with rest kit
I am sending my ASIHHTP code
please can any one migrate it to Rest kit, I unable to find the way
NSDictionary *dictionary=....;
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#auth/login",KBASEURL]];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setRequestMethod:#"POST"];
[request setValidatesSecureCertificate:NO];
[request addRequestHeader:#"Content-Type" value:#"application/json; charset=utf-8"];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dataDictionary options:kNilOptions error:nil];
[request setPostBody:(NSMutableData *)jsonData];
[request setContentLength:[jsonData length]];

RKObjectManager *manager = [RKObjectManager managerWithBaseURL:[NSURL URLWithString:#"https://172.22.221.117/api/v1.0/"]];
NSDictionary *dictionary=[NSDictionary dictionaryWithObjectsAndKeys:#"abc.com",#"email",#"password",#"password", nil];
[manager postObject:nil
path:#"auth/login"
parameters:dictionary
success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
}
failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
if(operation.HTTPRequestOperation.response.statusCode==200){
//do your processing
}
}];

Related

Storing JSON response in iOS error

I am making a call to an online php from my iOS app. In my output window I see the JSON Response with the data. But I need to store the NSString in my userdefaults but it is coming up NULL.
In this code the NSLog(#"JSON Response is %#", responseData); returns the json data just fine and I see the ipixid. But in the NSLog (#"ipixid is %#", ilixid); it returns ipixid is (null)
NSString *post =[[NSString alloc] initWithFormat:#"email=%#", strValue];
NSLog(#"PostData: %#",post);
NSURL *url1=[NSURL URLWithString:#"http://www.ipixsocial.com/membership/getresult.php"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url1];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if ([response statusCode] >=200 && [response statusCode] <300)
{
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"JSON Response is %#", responseData);
SBJsonParser *jsonParser = [SBJsonParser new];
NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
// NSString *username = [(NSString *) [jsonData objectForKey:#"email"]init];
NSInteger success = [(NSNumber *) [jsonData objectForKey:#"uid"] integerValue];
NSString* ipixid = [jsonData objectForKey:#"ipixid"];
[[NSUserDefaults standardUserDefaults] setObject:ipixid forKey:#"ipixid"];
NSLog (#"ipixid is %#", ipixid);
Don't ignore the "error" parameter you're passing to the parser. Also check that "jsonData" is not nil. I'm think that parsing is failing and because you're ignoring it and assuming jsonData is valid you're getting nil for [jsonData objectForKey:#"ipixid"];

NSUrlSession iso NSUrlConnection - uploading device token to a MySQL Database

I'm trying to update my code from NSUrlConnection to NSUrlSession. The app is running fine, no errors, but the token is never uploaded to the MySQL database... I've really no idea? Should I implement delegates or am I doing something basic stuff very wrong here? :-)
NSString *deviceToken = [[NSUserDefaults standardUserDefaults] objectForKey:#"deviceToken"];
//Information is only uploaded to SQLite database if 'deviceToken' is not null
if ([deviceToken length] > 0) {
NSURL *url = [NSURL URLWithString:#"http://sampleUrl.com/do.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *varString = [NSString stringWithFormat:#"deviceToken=%#", deviceToken];
NSData *requestData = [varString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setValue:#"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
/*NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:requestData completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
//Handle
}];*/
//NSURLSessionUploadTask *uploadTask2 = [session uploadTaskWithStreamedRequest:request];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
//Handle
}];
[dataTask resume];
Any ideas?
Thanks and regards,
Tom
I solved the problem:
NSString *deviceToken = [[NSUserDefaults standardUserDefaults] objectForKey:#"deviceToken"];
//Information is only uploaded to SQLite database if 'deviceToken' is not null
if ([deviceToken length] > 0) {
// Create URL and URLRequest
NSURL *url = [NSURL URLWithString:#"http://url.com/something.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//Create the body
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *varString = [NSString stringWithFormat:#"deviceToken=%#", deviceToken"]];
// Create POST parameters and add it to HTTPBody
[request setHTTPMethod:#"POST"];
[request setHTTPBody: [varString dataUsingEncoding:NSUTF8StringEncoding]];
// Set up a simple and asynchronous NSURLSession to send data to the php
// Set up the session configuration and header data
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
[config setRequestCachePolicy:NSURLRequestUseProtocolCachePolicy];
[config setHTTPAdditionalHeaders:#{
#"Accept" : #"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
#"Content-Type" : #"application/x-www-form-urlencoded",
#"Content-Length" : [NSString stringWithFormat:#"%lu", (unsigned long)[[varString dataUsingEncoding:NSUTF8StringEncoding] length]]
}];
// Create the session and the task
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
if (error)
NSLog(#"Connection failed! Error - %# %#",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
if (response)
{
NSLog(#"response description: %#", response.description);
[prefs setBool:YES forKey:#"tokenSent"];
}
if (data)
NSLog(#"data description: %#", data.description);
}];
// Start the task
[task resume];
}
Regards,
Tom

How to do this with AFNetworking?

I am trying to change my old 'ASIHTTP' code to AFNetworking, and stuck over this,
Can some one tell me how to convert this chunk of code to AFNetworking
NSString *urlString = [NSString stringWithFormat:kLogin];
NSURL *url= [NSURL URLWithString:urlString];
ASIFormDataRequest *request= [ASIFormDataRequest requestWithURL:url];
[activeRequests addObject:request];
[request setValidatesSecureCertificate:YES]; //SSL enforcement
[request addRequestHeader:#"Host" value:kHost];
[request addRequestHeader:#"Accept" value:#"application/xml, text/javascript, */*; q=0.01"];
[request addRequestHeader:#"Accept-Language" value:#"en-us,en;q=0.5"];
[request addRequestHeader:#"Accept-Encoding" value:#"gzip, deflate"];
[request addRequestHeader:#"Connection" value:#"keep-alive"];
[request addRequestHeader:#"X-Requested-With" value:#"XMLHttpRequest"];
[request addRequestHeader:#"Authorization" value:[NSString stringWithFormat:#"Basic %#", [Utils base64String:[NSString stringWithFormat:#"%#:%#", username, password]]]];
[request setDelegate:self];
[[ASIDownloadCache sharedCache] clearCachedResponsesForStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
[ASIHTTPRequest clearSession];
[request setTimeOutSeconds:REQUEST_TIME_OUT_SECS];
[request startAsynchronous];
I have tried AFHTTPClient along with request operation but stuck in the authentication part.
And getting Error 401.
The code which I have used for AFNetworking,
NSString *urlString = [NSString stringWithFormat:kLogin];
NSURL *url= [NSURL URLWithString:urlString];
AppHTTPClient* httpClient = [[AppHTTPClient alloc] initWithBaseURL:url];
[httpClient setDefaultHeader:#"Host" value:kHost];
[httpClient setDefaultHeader:#"Accept" value:#"application/xml, text/javascript, */*; q=0.01"];
[httpClient setDefaultHeader:#"Accept-Language" value:#"en-us,en;q=0.5"];
[httpClient setDefaultHeader:#"Accept-Encoding" value:#"gzip, deflate"];
[httpClient setDefaultHeader:#"Connection" value:#"keep-alive"];
[httpClient setDefaultHeader:#"X-Requested-With" value:#"XMLHttpRequest"];
[httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];
[httpClient setAuthorizationHeaderWithUsername:username password:password];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"GET"
path:nil
parameters:nil];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.allowsInvalidSSLCertificate = YES;
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"2");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog([error localizedDescription]);
NSLog(operation.responseString);
}
];
[operation start];
Use the AFHTTPClient setAuthorizationHeaderWithUsername:password: method to deal with the authentication. It should work, at least in my case it does.
Solved !!
The 'ASIHTTP' was by default adding the 'User-Agent', as
'App_Name_with_Version (iPad Simulator; iPhone OS 6.0; en_US)' and AFNetworking as not.
So I added this during the request creation and its working now.

pass local declaration of NSDictionary to performSelector

How it do so that I will not need to put data object right in selector call method?
code with warning (Local declaration of data) :
NSDictionary *data = [NSDictionary dictionaryWithObjectsAndKeys:#"SiluetaImage", #"ACTION", silueta_id, #"siluetaid", siluetaTyp_id, #"siluetatypid", nil];
[self performSelector:#selector(downloadBinDataForTyp:data:)
withObject:#"SiluetaImage"
withObject:data];
code without warning :
[self performSelector:#selector(downloadBinDataForTyp:data:)
withObject:#"SiluetaImage"
withObject:[NSDictionary dictionaryWithObjectsAndKeys:#"SiluetaImage", #"ACTION", silueta_id, #"siluetaid", siluetaTyp_id, #"siluetatypid", nil]];
the selector:
- (void)downloadBinDataForTyp:(NSString *)typ data:(NSDictionary*)data
{
ASINetworkQueue *q = [self queue];
NSString *sUrl = #"url_web_service";
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:sUrl]];
NSString *msgLength = [NSString stringWithFormat:#"%d", [[self getMsg] length]];
[request setTimeOutSeconds:60];
[request addRequestHeader: #"Content-Type" value:#"text/xml; charset=utf-8"];
[request addRequestHeader: #"SOAPAction" value:_action];
[request addRequestHeader: #"Content-Length" value:msgLength];
[request setRequestMethod: #"POST"];
request.userInfo = data;
[request appendPostData:[self getMsg]];
[request setDelegate:self];
[q addOperation:request];
[q go];
}
NSDictionary *data = [NSDictionary dictionaryWithObjectsAndKeys:#"SiluetaImage", #"ACTION", silueta_id, #"siluetaid", siluetaTyp_id, #"siluetatypid", nil];
[self performSelector:#selector(downloadBinDataForTyp:data:)
withObject:#"SiluetaImage"
withObject:data];
In this you are passing data whose scope is just to the method. And outside the method it can not be accessed, as it is getting released.

ASIHttpRequest upload image

Hey i have a mac application with the following code:
NSURL *url;
url = [NSURL URLWithString:#"http://yfrog.com/api/xauth_upload"];
ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];
[request setDelegate:self];
[request setUseCookiePersistence:NO];
[request setUploadProgressDelegate:self];
[request showAccurateProgress];
[request signRequestWithClientIdentifier:#"w" secret:#"x" tokenIdentifier:#"y" secret:#"z" usingMethod:ASIOAuthHMAC_SHA1SignatureMethod];
[request setPostValue:#"a" forKey:#"key"];
NSData *imageData = [[NSData alloc]initWithContentsOfFile:[draggedFilenames objectAtIndex:0]];
[request setPostValue:imageData forKey:#"media"];
[request startAsynchronous];
But the problem is i always get this response from yfrog servers:
So something is wrong with the image upload. On iPhone it works like this:
[request setData:UIImageJPEGRepresentation(picture, 0.8) withFileName:#"filename.jpg" andContentType:#"image/jpeg" forKey:#"media"];
But this doesn't work cocoa(mac) because there is no method like UIIMageJPEGRepresentation.
Also the authentication works, this cant be the problem. If you ask you about this method signRequestWithClientIdentifier it is from the asihttprequest+oauth wrapper from here:
https://github.com/keybuk/asi-http-request-oauth
So how can i upload the image correctly ?
Thanks so much.
NSData* NSImageJPEGRepresentation(NSImage* image, CGFloat compressionQuality)
{
if(nil == image)return nil;
NSDictionary *dict;
dict = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat:compressionQuality],
NSImageCompressionFactor,
nil];
NSBitmapImageRep* imageRep;
imageRep = [NSBitmapImageRep imageRepWithData:[image TIFFRepresentation]];
return [imageRep representationUsingType:NSJPEGFileType
properties:dict];
}

Resources