URL with special character in Objective-c - objective-c

I'm trying to use this URL in my application so that, when the user provides the right info he will be able to log in:
NSData *data = [NSData dataWithContentsOfURL: [NSURL URLWithString:[NSString stringWithFormat:#"https://www.example.come/login/CheckEligibility?json={'username'%%3A'%#'%%2C'password'%%3A'%#'}", username.text,passowrd.text]]];
For some reason I'm getting the exception:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil'
and when I test the URL in the browser, it works fine and gives me the data I want.

Try this
NSString *str = [NSString stringWithFormat:#"https://www.example.come/login/CheckEligibility?json={'username':'%#','password':'%#'}", username.text, passowrd.text];
str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:str];
NSData *data = [NSData dataWithContentsOfURL:url];

You need to encode the string like:
[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

Related

Trying to get data from URL returns data is nil in objective c

I am currentley trying to retrieve data from this link: http://steamcommunity.com/market/priceoverview/?country=US&currency=3&appid=730&market_hash_name=%E2%98%85%20Bayonet
I want the data that the link outputs when you go and click it.
Here is my current code:
NSData *data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:#"http://steamcommunity.com/market/priceoverview/?country=US&currency=3&appid=730&market_hash_name=★%20Bayonet"]];
NSDictionary *test = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"%#", test[#"lowest_price"]);
But currentley it returns this error:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil'
I think it has something to do with the star that is involved in the URL string, does anyone have a solution for this?
Your original url, in the example code, is malformed.
First, here's the code that works:
#import <Foundation/Foundation.h>
int main(int argc, char *argv[]) {
#autoreleasepool {
NSError *error = nil;
// NOTE: I pruned the original '%20' in your example -- partially escaped strings
// are difficult to deal with.
NSString *urlString = #"http://steamcommunity.com/market/priceoverview/?country=US&currency=3&appid=730&market_hash_name=★ Bayonet";
// Now, escape the entire string
NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
// Looks good
NSLog(#"%#", [url absoluteString]);
// http://steamcommunity.com/market/priceoverview/?country=US&currency=3&appid=730&market_hash_name=%E2%98%85%20Bayonet
// Run it
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
NSDictionary *test = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"%#", test[#"lowest_price"]);
//129,99€
// Data is weird to me, but looks appropriate.
}
}
First, you didn't attempt to escape the string before using it. initWithString: docs state:
This method expects URLString to contain only characters that are
allowed in a properly formed URL. All other characters must be
properly percent escaped. Any percent-escaped characters are
interpreted using UTF-8 encoding.
So, we do that. However, the original string in the sample code was "partially escaped". If you escaped that URL, you'd end up with:
http://steamcommunity.com/market/priceoverview/?country=US&currency=3&appid=730&market_hash_name=%E2%98%85%2520Bayonet
instead of
http://steamcommunity.com/market/priceoverview/?country=US&currency=3&appid=730&market_hash_name=%E2%98%85%20Bayonet
... as you can see, the '%20' would itself get escaped to '%2520'.
I hope this helps. Cheers.
Edit:
Please check that there is error in the URL that you copied.
The actual URL is the one that you mentioned in the comments :
#"http://steamcommunity.com/market/priceoverview/?country=US&currency=3&appid=730&market_hash_name=%E2%98%85%20Bayonet"
NSData *data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:#"http://steamcommunity.com/market/priceoverview/?country=US&currency=3&appid=730&market_hash_name=%E2%98%85%20Bayonet"]];
NSDictionary *test = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"%#", test[#"lowest_price"]);

Contents from url to string

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.

NSData dataWithContentsOfURL erroneous?

Trying to parse simple URL with NSData but fails:
NSURL* url = [[NSURL alloc] initWithString:#"http://192.168.2.105:80"];
NSData* data = [NSData dataWithContentsOfURL:url options:NSDataReadingUncached error:&error];
Result is
error = Cocoa error 256
What reason?
Check out this:
NSURL* URL=[NSURL URLWithString: #"http://www.google.com"];
NSURLRequest* req=[NSURLRequest requestWithURL: URL];
NSData* data=[NSURLConnection sendSynchronousRequest: req returningResponse: nil error: nil];
That's a short example, I recommend to check out the response and the eventual error.
EDIT
You were right about using dataWithContentOfURL, the code that I posted does the same thing.
But it's the URL to be wrong.You should pass something like http://www.site.org .

NSInvalidArgumentException', reason: '-[__NSCFString isFileURL]: unrecognized selector sent to instance 0x712e450'

I am new to iPhone App development.
When I run a sample project, I did which parses an xml feed and displays the contents along with image in a table view, I get this error -
"NSInvalidArgumentException', reason: '-[__NSCFString isFileURL]: unrecognized selector sent to instance 0x712e450'"
It is occurring only when I try to display the image in UITableViewCell.
The code I used for getting images from url is -
if([elementName isEqualToString:IMAGE])
{
NSURL *imageUrl = [attributeDict objectForKey:#"url"];
NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];
bbc.image = [UIImage imageWithData:imageData];
}
where bbc is a class(NSObject subclass) object used to store the parsed contents.
I think you are using NSString as NSURL. Try this:
NSURL *imageUrl =[NSURL URLWithString:[attributeDict objectForKey:#"url"]];
It looks like "url" is in fact an NSString, not an NSURL object. Convert it to an NSURL object yourself:
if ([elementName isEqualToString:IMAGE])
{
NSString *urlStr = [attributeDict objectForKey:#"url"];
NSURL *imageUrl = [NSURL URLWithString:urlStr];
NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];
bbc.image = [UIImage imageWithData:imageData];
}
imageURL is not a NSURL, but a string.

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