Restkit route error - objective-c

I am trying to do a simple post for a login screen. I post an email address and password. This gives me a JSON back with status-codes. If this code is 200 it also contains a person object. If it is something else it contains an error object.
I have this code for posting.
RKObjectManager *manager = [RKObjectManager managerWithBaseURL:[NSURL URLWithString:#"http://******.com.be/nl/webservice/company-user/login/apikey/key**"]];
NSDictionary *dictionary = #{ #"email": _txtLogin.text, #"pwd": _txtPass.text};
NSMutableURLRequest *request = [manager requestWithObject:nil method:RKRequestMethodPOST path:nil parameters:dictionary];
RKObjectRequestOperation *operation = [manager objectRequestOperationWithRequest:request success:^(RKObjectRequestOperation *operation, RKMappingResult *result) {
NSLog(#"Loading mapping result: %#", result);
}
failure:nil];
[operation start];
But this code is causing the following error.
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid parameter not satisfying: route'
*** First throw call stack:
Could anybody help me? I'm new to restkit.
Kind regards

You're trying to post an object using automatic routing, however, your object is nil. Therefore, it will rely on the path parameter to work out where to POST to. This is also nil.
You need to create the object manager with a common base URL, eg. http://******.com.be/nl/webservice/company-user and supply your method with the path parameter /login/apikey/key**

Related

Suppressing Core Data errors from addPersistentStoreWithType:

I have a custom NSIncrementalStore. If there's a problem adding it, the error is automatically logged to the console.
The problem is that the options can contain sensitive data that I obviously don't want logged to the console.
I presume the error is logged by Core Data, which I don't really need, since I already have an NSError argument that I can use appropriately.
For example:
#implementation FakeStore
- (BOOL)loadMetadata:(NSError **)error {
*error = [NSError errorWithDomain:#"faildomain" code:531 userInfo:nil];
return NO;
}
#end
Attempt at adding the store:
[NSPersistentStoreCoordinator registerStoreClass:[FakeStore class] forStoreType:#"FakeStore"];
...
NSDictionary *options = #{#"option": #"sensitivedata"};
NSError *error;
[persistentCoordinator addPersistentStoreWithType:#"FakeStore" configuration:nil URL:storeUrl
options:options error:&error];
The error that is automatically logged to the console:
CoreData: error: -addPersistentStoreWithType:FakeStore configuration:(null) URL:<URL> options:{
option = sensitivedata;
} ... returned error Error Domain=faildomain Code=531 "The operation couldn’t be completed. (faildomain error 531.)" with userInfo dictionary {
}
A workaround is that the sensitive data shouldn't be passed into the options for my store, but it shouldn't be necessary.
Is there anyway to suppress this error?
well you can't turn it off but you should be able to redirect it. Bummer.. needs private API .. is that an option for you?
https://www.google.de/search?client=safari&rls=en&q=_NSSetLogCStringFunction&ie=UTF-8&oe=UTF-8&gfe_rd=cr&ei=uUKdVe-QN4nj8wfl9AE
tried the first link and found it still worked!
if private API is no option: no (and Id file a bug :D)

EXC_BAD_ACCESS when doing a POST using AFNetworking 2.0

My code:
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager] ;
manager.requestSerializer = [AFJSONRequestSerializer serializerWithWritingOptions:NSJSONReadingAllowFragments];
manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
[manager POST:[_urlBase stringByAppendingPathComponent:_urlRequest]
parameters:paramDictionary
success:^(NSURLSessionDataTask *task, id responseObject){
dispatch_async(dispatch_get_main_queue(),^{
[self AFRequestFinished:responseObject];
});
}
failure:^(NSURLSessionDataTask *task, NSError *error){
NSLog(#"JSON ERROR PARAMETERS: %#", error);
}
];
I am using this POST request to send several types of data up to a server along with pictures. I am using something very similar for the GET request and it works fine. Whenever I run this code I get a EXC_BAD_ACCESS CODE=1 error on the following line of AFNetworking 2.0. The responseObject is 0x0:
responseObject = [self.responseSerializer responseObjectForResponse:task.response data:[NSData dataWithData:self.mutableData] error:&serializationError];
The above line of code is within the if/else method in:
- (void)URLSession:(__unused NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
UPDATE
I ran instruments on the code, and it there is a zombie present. AFNetworking is trying to make a call to the NSError, but it has been deallocated. I believe this has arisen because the POST call initially succeeds, but there is still an error that is flagged. So it initially thinks there is no error and sets it to nil, but then tries to call for it in the error block of the POST.
If you're using the most recent version, you may be experiencing this known issue when the JSON serializer returns an error. You can work around this until a new release is made by:
removing the #autoreleasepool in the serializer, or
changing the scope of the error to outside the autorelease pool
(Both solutions are outlined in the issue linked above.)
On a side note, there's no need to dispatch to the main queue in the completion handler. AFNetworking guarantees that completion blocks are called on the main thread.

Exception when trying to fetch channelId using the youtube api in objective c

I am trying to fetch youtube channel id using the google-api-objectivec-client. The problem I am having is basically that for some reason I am receiving exception when trying to access the channelId. The code I am using:
GTLServiceYouTube *service = [[GTLServiceYouTube alloc] init];
service.APIKey = _MY_API_KEY_;
GTLQueryYouTube *query = [GTLQueryYouTube queryForSearchListWithPart:#"id"];
query.q = #"google";
query.type = #"channel";
query.maxResults = 1;
GTLServiceTicket *ticket = [service executeQuery:query completionHandler:^(GTLServiceTicket *ticket, id object, NSError *error) {
if (error == nil) {
GTLYouTubeSearchListResponse *products = object;
for (id item in products.items) {
GTLYouTubeSearchResult *result = item;
NSLog(#"Identifier:%#",result.identifier);
GTLYouTubeResourceId* resourceId = result.identifier;
NSLog(#"kind:%#",resourceId.kind);
NSLog(#"channel:%#",resourceId.channelId);
}
}else{
NSLog(#"Error: %#", error.description);
}
}];
The output I get when i am running this code is:
2013-04-05 11:37:12.615 YouTest[21704:11303] Identifier:GTLYouTubeChannel 0x7233b00: {kind:"youtube#channel" channelId?:"UCK8sQmJBp8GCxrOtXWBpyEA"}
2013-04-05 11:37:12.617 YouTest[21704:11303] kind:youtube#channel
2013-04-05 11:37:12.617 YouTest[21704:11303] -[GTLYouTubeChannel channelId]: unrecognized selector sent to instance 0x7233b00
2013-04-05 11:37:12.618 YouTest[21704:11303] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[GTLYouTubeChannel channelId]: unrecognized selector sent to instance 0x7233b00'
So my implementation crashes on the point where I am trying to access the channelId of the resourceId. From the documentation I understood that the channelId should be there as the type of the resourceId is youtube#channel. The channelId can be off course parsed from the result.identifier string that I am also printing, but since there is a property for the channelId I would prefer using that.
Any ideas about what is wrong with my code?
There is indeed a bug in the Google libraries. However I solved this problem by accessing the JSON string directly and parsing it with the help of the NSString+SBJSON.h class, as in this example.
#import "NSString+SBJSON.h"
...
GTLYouTubeResourceId *resource = channel.snippet.resourceId;
NSDictionary *jsonObject = [resource.JSONString JSONValue];
NSString *channelid = [jsonObject valueForKey:#"channelId"];
I'm not very familiar with Objective-C, but yeah, that looks like there's something wrong with the generated client library's YouTube Data API v3 bindings. Are you using the latest version from the project page? You might want to file a bug against the client library if you can reproduce it with the latest version. While troubleshooting this further, I'd check to see if you have the same problem when query.type = #"video"; and you try to access the videoId of the response item.
Here's an alternative you could try, though. The channel's id is also returned in the snippet.channelId property. If you request the snippet part via GTLQueryYouTube *query = [GTLQueryYouTube queryForSearchListWithPart:#"snippet"]; see if you can read that value instead.
I had the same issue. Solved it with the following...
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:[resourceId.JSONString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
NSString *channelId = [jsonObject valueForKey:#"channelId"];
NSLog(#"channelId is %#", channelId);
Workaround Code:
channel.snippet.resourceId.JSON[#"channelId"];
No need to parse the JSON yourself as the underlying JSON is exposed.
It looks like the automatic binding is not working for GTLYouTubeResourceId because the "kind" element of "youtube#channel" is throwing off the runtime object creation and creating a GTLYouTubeChannel instead.
Thorough Workaround Code:
ticket.surrogates = #{ (id)[GTLYouTubeChannel class] : [GTLYouTubeResourceId class] };
If you really want to force that binding to work you can workaround a little further upstream on the ticket when you execute the query.
Global Workaround Patch:
https://github.com/google/google-api-objectivec-client/pull/109
There's open tickets for the issue:
https://github.com/google/google-api-objectivec-client/issues/63
https://github.com/google/google-api-objectivec-client/issues/92
It seems they want to change the API to not call the resourceId.kind 'kind' to avoid this problem. But while we wait for the API to change, any of these three workarounds should serve your purposes.

Parse JSON with iOS 6 and xCode 4.5.2

I'm new in objective-c and and building a sign in page for a specific website. When the user provide information the following JSON return back from the server:
{
"object":{},
"resultCode":0,
"resultMessage":"You successfully signed in "
}
And this what I'm trying to do based on a tutorial I found:
-(IBAction)login{
// Download JSON
NSData *data = [NSData dataWithContentsOfURL: [NSURL URLWithString:[NSString stringWithFormat:#"https://www.example.com/login?username=%#&password=%#", nationalID.text,passowrd.text]]];
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *response = [json objectForKey:#"resultMessage"];
NSLog(#"response %#",response);
}
I want to log out "resultMessage" but somehow it throws an exception:
2012-12-13 06:46:50.607 myProject[7178:11303] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil'
*** First throw call stack:
(0x1c8d012 0x10cae7e 0x1c8cdeb 0xbff817 0x2f1a 0x10de705 0x15920 0x158b8 0xd6671 0xd6bcf 0xd5d38 0x4533f 0x45552 0x233aa 0x14cf8 0x1be8df9 0x1be8ad0 0x1c02bf5 0x1c02962 0x1c33bb6 0x1c32f44 0x1c32e1b 0x1be77e3 0x1be7668 0x1265c 0x279d 0x26c5)
libc++abi.dylib: terminate called throwing an exception
Looks like the -dataWithContentsOfURL: message failed and returned nil, which is exactly what the error message says. You need to confirm that your -stringWithFormat: message is giving you the correct URL format, and check whether the server is returning what you expect.
if you could observe the issue description:
'NSInvalidArgumentException', reason: 'data parameter is nil'
means the response from your response from the web url is nil or NULL
this is not a issue related to JSON parser.
Looks like you have a simple typo, you are using:
nationalID.text,passowrd.text
You probably meant to not misspell 'password'.
First Try static url like:
https://www.example.com/login?username=admin&password=123
if this returns you correct response then try Property Variables like:
https://www.example.com/login?username=self.username.text&password=self.password.text
And one mistake you have made is that resultMessage is string not an Array.
Hope this helps you

Why does NSMutableURLRequest instantiation cause a crash?

I am trying to create a NSMutableURLRequest like this:
NSURL *URLWithString = [
NSString stringWithFormat:#"%#?%#",
urlString,
datas
];
NSMutableURLRequest* request = [[[NSMutableURLRequest alloc] initWithURL:URLWithString] autorelease];
When I run it on my iPhone 4S, the app crashes and I get the following exception:
2012-10-30 15:58:53.495 [429:907] -[__NSCFString absoluteURL]:
unrecognized selector sent to instance 0x1cd74a90
2012-10-30 15:58:53.497 [429:907] --- Terminating app due to uncaught
exception 'NSInvalidArgumentException', reason: '-[__NSCFString
absoluteURL]: unrecognized selector sent to instance 0x1cd74a90'
--- First throw call stack:
(0x361b62a3 0x344c697f 0x361b9e07 0x361b8531 0x3610ff68 0x3611363f
0x320396e7 0x32039551 0x320394ed 0x33bde661 0x33bde597 0x387e1
0x376d9f1f 0x376da9a9 0x341c535d 0x3618b173 0x3618b117 0x36189f99
0x360fcebd 0x360fcd49 0x366392eb 0x374db301 0x37cc1 0x37c58)
libc++abi.dylib: terminate called throwing an exception
What's wrong?
Lots of issues:
For a start look into how to invoke NSString and NSURL methods. I have done it for the code you have pasted.
NSURL * myUrl = [NSURL URLWithString:[NSString stringWithFormat:#"%#?%#",urlString,datas]];
and
NSMutableURLRequest* request = [[[NSMutableURLRequest alloc] initWithURL:myUrl] autorelease];
Your NSURL creation code is wrong.
NSURL *URLWithString = [NSString stringWithFormat: #"%#?%#", urlString, datas];
Here, you are trying to create an NSURL directly with an NSString class method (stringWithFormat). The result is that your variable URLWithString will be of the wrong type, and when you send it an NSURL message you'll get a crash like you are getting.
To fix this you need to create an NSString of the URL address first, and instantiate an NSURL using that, like so:
NSString *completeURLString = [NSString stringWithFormat:#"%#?%#", urlString, datas];
NSURL *completeURL = [NSURL URLWithString: completeURLString];
(Technically, these two lines can be combined; I've separated them to make it clear what's going on.)
Also, whilst probably not related to your crash, you shouldn't call your URL variable URLWithString, as that is the name for a class method of NSURL. Make sure to come up with a unique name for it, and to start it with a lower case character (at the very least, this will make your code easier to decipher for others).