Contents from url to string - objective-c

NSString *urlAddress = [NSString stringWithFormat:#"http://www.domain.com?input=%#",[alertView textFieldAtIndex:0].text];
NSURL *myUrl = [NSURL URLWithString:[urlAddress stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSString *openURL = [NSString stringWithContentsOfURL:myUrl encoding:NSUTF8StringEncoding error:NULL];
NSLog(#"%#",openURL);
openUrl is always returning (null), probably because of the encoding, but I don't know how to fix it.

Double check these three things:
Check that the URL which you are pointing to is a valid URL. The null value could be a result of an invalid URL.
Catch the NSError which the stringWithContentsOfURL throws. That will give you some insight on what is wrong.
Like you suspect, try changing the string encoding.

NSError *error;
NSString *urlString = [NSString stringWithFormat:#"http://www.domain.com?input=%#", stringVariable];
NSURL *urlAdress = [NSURL URLWithString:urlString];
NSString *urlContent = [[NSString alloc] initWithContentsOfURL:urlAdress encoding:NSUTF8StringEncoding error:&error];
NSLog(#"%#", urlContent);
This works fine, the problem was an failing internet connection.

Related

Is there an easy way to shorten URL's with parameters in Objective C using goo.gl?

This does not seem to be working:
NSString *key = #"mykey";
NSString *shortenedStrURL = [NSString stringWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"https://www.googleapis.com/urlshortener/v1/url?key=%#&longUrl=%#", key,strURL]] encoding:NSUTF8StringEncoding error:nil];
return [NSURL URLWithString:strURL];

Uploading Photo with ASIHTTPRequest

I'm using ASIHTTPRequest to upload a photo with PHP. The PHP side is proven to work(I'm using it for android), and I'm trying to get the iOS component to work.
Here is my upload:
NSString *myurl = #"http://mydomain.tld/php/upload.php?casenum=";
myurl = [myurl stringByAppendingFormat: casenumber];
NSString *fixedURL = [myurl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSString stringWithFormat:#"%#",fixedURL];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
NSData *imageData = UIImageJPEGRepresentation(image1.image, 90);
[request setData:imageData withFileName:#"myphoto.jpg" andContentType:#"image/jpeg" forKey:#"file"];
[request setCompletionBlock:^{
NSString *responseString = [request responseString];
NSLog(#"Response: %#", responseString);
}];
[request setFailedBlock:^{
NSError *error = [request error];
NSLog(#"Error: %#", error.localizedDescription);
}];
[request startAsynchronous];
Ive found this on the internet and when I run it, it fails with the error 2012-01-17 10:52:16.939 MyApp[30373:707] Error: NSInvalidArgumentException
From many of the documentation and examples I've found online, this should work, but it isn't, as you can see with the exception. Any help at ironing out the kinks? If you need any other information, I'll gladly post it.
There would appear to be a couple of errors in the way that you're producing the NSURL. Firstly, it's only the parameters that need escaping, not the whole URL, so
NSString *myurl = #"http://mydomain.tld/php/upload.php?casenum=";
myurl = [myurl stringByAppendingFormat: casenumber];
NSString *fixedURL = [myurl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
should be
NSString *myurl = #"http://mydomain.tld/php/upload.php?casenum=";
NSString *escapedCasenumber = [casenumber stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
myurl = [myurl stringByAppendingFormat:escapedCasenumber];
Secondly, you're then trying to assign an NSString to an NSURL, so
NSURL *url = [NSString stringWithFormat:#"%#",fixedURL];
should be
NSURL *url = [NSURL urlWithString:myurl];
Finally, the second argument passed to UIImageJPEGRepresentation should be a float value between 0.0 and 1.0, so I'm guessing
NSData *imageData = UIImageJPEGRepresentation(image1.image, 90);
should be
NSData *imageData = UIImageJPEGRepresentation(image1.image, 0.9);
If it still doesn't work after these changes, then do as JosephH suggests and use the debugger to identify exactly which line is causing the exception

NSURL returns Nil Value

Here Below is my code
NSString *string = [NSString stringWithFormat:#" http://abc.com /Demo/View.php?drinkId=%#&name=%#&comment=%#&date=%#&rating=%#& ReqestType=SubmitComment",DrinkId,Name,Comment,Date,Rating];
NSURL *url = [[NSURL alloc] initWithString:string];
Here in string there is value but url returns nil.
Can Anyone tell why this happened.
Thanks ....
"This won't work, so here's what I did instead"
NSString *string = [NSString stringWithFormat:#"http://abc.com/Demo/View.php?drinkId=%#&name=%#&comment=%#&date=%#&rating=%#&ReqestType=SubmitComment",DrinkId,Name,Comment,Date,Rating];
NSURL *url = [[NSURL alloc] initWithString:string];
NSURL will return nil for URLs that contain illegal chars, like spaces.
Before using your string with [NSURL URLWithString:] make sure to escape all the disallowed chars by using [NSString stringByAddingPercentEscapesUsingEncoding:].
Here is the class reference for NSString.
Hi All Now My Problem Is solved here I did a mistake left a blank space before "http".
The correct code is
NSString *string = [NSString stringWithFormat:#"http://myserver.com/Demo/View.php?drinkId=%#&name=%#&comment=%#&date=%#&rating=%#&ReqestType=SubmitComment",DrinkId,Name,Comment,Date,Rating];
NSURL *url = [[NSURL alloc] initWithString:string];

Crash on writeToFile

I'm using quite a simple method of storing file names in a text file. For some reason when I initiate the writeToFile I get a crash:
pathString = [NSString stringWithFormat:#"New FileName - %#.png", identifier];
NSString *currentContents = [NSString stringWithContentsOfFile:saveFilePath encoding:NSUTF8StringEncoding error:nil];
NSString *newContents = [NSString stringWithFormat:#"%#:::%#",currentContents, pathString];
NSData *newData = [newContents dataUsingEncoding:NSUTF8StringEncoding];
[newData writeToFile:saveFilePath options:NSDataWritingAtomic error:nil];
It reads the file, places it's contents into a variable called currentContents, then adds the new string to the file, and re-writes it. What's going wrong here.
Without the writeToFile line it works, with it, I get a crash.
Origin of saveFilePath
NSString *saveDocument = [NSString stringWithFormat:#"SavedFile.txt"];
NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
saveFilePath = [docsDirectory stringByAppendingPathComponent:saveDocument];
An NSLog of saveFilePath reveals a correct path
I think your problem might actually be a missing null character ('\0') at the end of your NSData object. So you finally end up with messed up data. You might want to use -writeToFile:atomically:encoding:error: on your new string right away anyway.
It turns out that the reason the file wasn't writing was because of an unallocated variable:
NSString *currentContents = [NSString stringWithContentsOfFile:saveFilePath encoding:NSUTF8StringEncoding error:nil];
should have been:
NSString *currentContents = [[NSString alloc] initWithContentsOfFile:saveFilePath encoding:NSUTF8StringEncoding error:nil];

What's the equivlent code for stringWithContentsOfURL using a NSURLRequest?

NSURL *url = [NSURL URLWithString:escapedUrlString];
NSString *responseString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
But, I was reading online that I should probably be using an NSURLRequest instead if I want to add a timeout. The first code works fine, but the second code always returns #"" (not nil, just ""). Anyone have any suggestions?
I also read that the NSURLConnection takes care of any sort of web compression that might be done whereas NSURLRequest won't handle that, so I thought I better just go for the more well rounded solution.
http://lists.apple.com/archives/cocoa-dev/2009/Oct/msg01921.html
NSString *escapedUrlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *responseString;
NSURLResponse *response;
NSError *error;
NSURLRequest *request = [[NSMutableURLRequest alloc]
initWithURL:[NSURL URLWithString:escapedUrlString]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:5]; // 5 second timeout?
NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if(responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]){
NSLog(#"Recieved String Result: %#", responseString);
} else {
NSLog(#"Response String is null!");
}
Thanks for the good suggestions. The code magically worked this morning, so I'm guessing my webserver went down or something last night.