NSError code 256 - Twitter GET - objective-c

I have this code here which sometimes works. I make sure that I am connected to the internet before attempting this Get from Twitter, and I am pretty sure it isn't the problem.
...
NSString *twitterURLString = [NSString stringWithFormat:#"https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=twitterapi&count=2"];NSURL *url = [NSURL URLWithString:twitterURLString];
NSError *error = nil;
NSData *dataFromURL = [NSData dataWithContentsOfURL:url
options:0
error:&error];
NSLog(#"%#", error);
...
This returns the following :
Error Domain=NSCocoaErrorDomain Code=256 "The operation couldn’t be completed. (Cocoa error 256.)" UserInfo=0x4f6520 {NSURL=https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=twitterapi&count=2}
I'm sure it has to do with the url encoding or something since the actual link works well. Also, it actually works sometime, with the same internet connexion (which I repeat is tested and works fine). Any ideas would be greatly appreciated!

Related

Json, weird Bugs for parse for Xcode

I need to mention something before i explain the bugs.
The JSON format is valid, and the code has works fine also.
when i pull the data from the server, the data SOMETIME will got error.
When i try to NSLog the return, and below is the error return.
Error parsing JSON: Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Unterminated string around character 2424.) UserInfo=0x956f200 {NSDebugDescription=Unterminated string around character 2424.}
On my Iphone 4, it works fine. But it will always fail to get data Xcode SDK or Iphone 5s, even all is running the same apps.
This this i upload is the return data(just show you how huge data for the return).
NSString *returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Data > %#",returnString);
SBJsonParser *jsonParser = [SBJsonParser new];
NSError *thiserror;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &thiserror];
parseData = (NSDictionary *) [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &thiserror];
if (!jsonArray) {
NSLog(#"Error parsing JSON: %#", thiserror);
}
On the returnString nslog, it had return the complete data.
On the jsonArray, it always go false, means will display the error
Now i trying to assume because the json is too large, so the connection speed will make the return be error. but i not really got idea how to solve it. Is that i looking on wrong direction? or any one can give me hints how to solve this problem? thanks!

data parameter is nil when i trying to fetch the data from web service using json

- (NSDictionary*)PostWebService:(NSString*)completeURL param:(NSString*)value
{
#try
{
NSString *urlStr =[completeURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
//NSString *urlPart=#"req=value";
//NSString *urlPart;
NSString *urlPart=[NSString stringWithFormat:#"req=%#", value];
NSLog(#"String %#",urlPart);
NSData *requestBody = [urlPart dataUsingEncoding:NSUTF8StringEncoding];
//NSLog(#"String %#",requestBody);
[request setHTTPBody:requestBody];
NSURLResponse *response = NULL;
NSError *requestError = NULL;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] ;
NSLog(#"String %#",responseString);
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions
error:&error];
return json;
}
#catch(NSException *e)
{
NSLog(#"reason is%#",e.reason);
}
}
and i call this method here..
-(NSDictionary*)gotvall:(NSString*)req
{
#try
{
NSString *vurl=#"some url/";
// vurl=[vurl stringByAppendingString:#"req="];
// vurl=[vurl stringByAppendingString:req];
// NSLog(#"%#",vurl);
NSDictionary *json=[self PostWebService:vurl param:req];
NSLog(#"json is%#",json);
return json;
}
#catch(NSException *e)
{
NSLog(#"%#",e.reason);
}
}
After debugging this method I got result as data parameter is nil.
Can anyone tell that what I am doing wrong here.
I got the complete url and when I run that url on browser I got the perfect data but when I printing the value of json it returns null.
You reported that your error was:
Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL" UserInfo=0x8d84960 {NSErrorFailingURLStringKey=%20http://www.hugosys.in/www.nett-torg.no/api/vehicl‌​e/, NSErrorFailingURLKey=%20http://www.hugosys.in/www.nett-torg.no/api/vehicle/, NSLocalizedDescription=unsupported URL, NSUnderlyingError=0x8d8bfe0 "unsupported URL"}
That %20 in your error message is a space at the start of your URL that your stringByAddingPercentEscapesUsingEncoding call converted to %20. If you remove that extra space, you should be in good shape.
A couple of other observations:
Just to warn you, your use of stringByAddingPercentEscapesUsingEncoding will correctly handle the presence of a space in the req value. But it will not properly handle the presence of certain other characters (notably & or +). If it's possible that those sorts characters might appear in the req value, you might want to remove the call to stringByAddingPercentEscapesUsingEncoding for the whole URL, and instead just use CFURLCreateStringByAddingPercentEscapes (which gives you a little more control over the percent escaping process) on just the req value. See the percentEscapeString method in this answer: Append data to a POST NSURLRequest.
In both your network request as well as your JSON parsing process, you are returning an NSError object. I might suggest that you log those values if they're ever non-nil, which will help you diagnose problems in the future.
I notice that you are using exception handling. That's not common in Objective-C. As the Programming in Objective-C guide says:
Dealing with Errors
Almost every app encounters errors. Some of these errors will be outside of your control, such as running out of disk space or losing network connectivity. Some of these errors will be recoverable, such as invalid user input. And, while all developers strive for perfection, the occasional programmer error may also occur.
If you’re coming from other platforms and languages, you may be used to working with exceptions for the majority of error handling. When you’re writing code with Objective-C, exceptions are used solely for programmer errors, like out-of-bounds array access or invalid method arguments. These are the problems that you should find and fix during testing before you ship your app.
All other errors are represented by instances of the NSError class. This chapter gives a brief introduction to using NSError objects, including how to work with framework methods that may fail and return errors. For further information, see Error Handling Programming Guide.
Bottom line, As I mentioned in the second point, you should be checking NSError return values yourself rather than relying on exceptions in Objective-C.

Xcode 5 [NSString writeToFile] without absolute path

I've checked out a few other posts about this topic, but I am still left with some doubt on whether or not [NSString writeToFile] is writing to the relative path.
NSError *error = nil;
BOOL success = [str writeToFile:#"someFile.txt"
atomically:YES
encoding:NSUTF8StringEncoding
error:&error];
NSString *status = success ? #"Success" : #"Failure";
if(success){
NSLog(#"Done Writing: %#",status);
}
else{
NSLog(#"Done Writing: %#",status);
NSLog(#"Error: %#",[error localizedDescription]);
}
writeToFile works when given the path to a certain folder and by NSLogging the error, I can see what kind of error occurs. However, when running the above code, no error occurs and after having done a thorough search, I think I can safely say that a file was never created. What's going on behind the scenes?
Well it's certainly working, which you confirm yourself as your code traps and reports errors very nicely. Your only issue is that you don't know where the file is being written to, and in this case, as no path has been specified it will be to the current working directory, which is a concept in pretty much all operating systems (even Windows!).
I must admit that I don't know what the default current working directory is under iOS, but you can find out yourself with:
NSString *cwd = [[NSFileManager defaultManager] currentDirectoryPath];
NSLog(#"cwd='%#'", cwd);

Objective-C error handling

anyone know how I can handle error code when there is an error on the following:
database_flag = [NSString stringWithContentsOfURL:database_flag_query encoding:NSASCIIStringEncoding error:&error];
TO explain more please find below my code
Basically I want to check mysql for a flag
if the flag is 1 then i get the ip address of the stream from the databse
else i use the local one store.
the only issue is when there is not access to the mysql server the program gets stuck!!
database_flag_query = [NSURL URLWithString:#"http://192.168.0.20/iqkradio_stream_ip_flag.php"];
database_flag = [NSString stringWithContentsOfURL:database_flag_query encoding:NSASCIIStringEncoding error:&error];
database_flag = [database_flag stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if ([database_flag isEqualToString: #"1"])
{
NSLog(#"URL flag is set");
database_url_query = [NSURL URLWithString:#"http://192.168.0.20/iqkradio_stream_ip_url.php"];
database_url = [NSString stringWithContentsOfURL:database_url_query encoding:NSASCIIStringEncoding error:&error];
database_url = [database_url stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
url1 = [NSURL URLWithString:[database_url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSLog(database_url);
}
else
{
NSLog(#"URL flag is not set, Reverting to stored value");
url1 = [NSURL URLWithString: [NSString stringWithFormat: #"http://radio.qkradio.com.au:8382/listen.mp3"]];
}
streamer = [[AudioStreamer alloc] initWithURL:url1];
EDIT - NSURLConnection & Timeouts - Based on the additional information and the comment stream below, and to put information in the answer (rather than the long comment stream):
see accepted answer to this question here for the timeout example. For the NSURLConnection example, checkout the apple documentation here
General Error Handling -
The following link may be helpful --> http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/ProgrammingWithObjectiveC/ErrorHandling/ErrorHandling.html.
"Before you call this method, you’ll need to create a suitable pointer so that you can pass its address:
NSError *anyError;
BOOL success = [receivedData writeToURL:someLocalFileURL
options:0
error:&anyError];
if (!success) {
NSLog(#"Write failed with error: %#", anyError);
// present error to user
}
If an error occurs, the writeToURL:... method will return NO, and update your anyError pointer to point to an error object describing the problem.
When dealing with errors passed by reference, it’s important to test the return value of the method to see whether an error occurred, as shown above. Don’t just test to see whether the error pointer was set to point to an error."
So, for your issue, try adding:
if(!database_flag)
{
//call your error handling function
[myFunction withError: error];
}
before trimming the database_flag. If your connection isn't working, then you need to handle it before continueing to your if([database_flag isEqualToString:... code.
If that doesn't solve the problem, can you give some information/log statements on where/what the error is that is halting your application?
Hope that helps.

NSJSONSerialization not working as intended for Stack overflow API

I am trying to use NSJSONSerialization to serialize the data returned from stack overflow API, but it is not working as intended :(
I am using code as below :
NSURL *apiURL = [NSURL URLWithString:#"http://api.stackoverflow.com/1.1/questions?tagged=objective-c&pagesize=30"];
NSError *error = nil;
// First option - failed
NSInputStream *inputStream = [NSInputStream inputStreamWithURL:apiURL]; // returning nil
id jsonFound1 = [NSJSONSerialization JSONObjectWithStream:inputStream options:NSJSONReadingMutableContainers error:&error];
// Second option - failed
NSData *jsonData = [NSData dataWithContentsOfURL:apiURL]; // returning correct value, verified after converting it to NSString
id jsonFound2 = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error]; // returning nil
I am trying the above code in Xcode 4.2 for iOS5 and I am getting (null) for inputStream and for jsonFound2.
Earlier I was doing it through SBJSON and it was working correctly.
Can anyone suggest me if I am doing anything wrong or missing anything?
I think there may be a missing step after assigning an inputStream.
[inputStream open];
I have not tried this with remote URLs, but have seen examples that use this approach.
First option does not work because it supports only file url (thanks to David for pointing).
Second option works fine for remote urls.