Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSURL URLWithString:myString returns Nil?

I have a string of my url.. I want to get data from that url. For that I needs to create object of NSURL. The problem is while I try URLWithString method of NSURL class it returns nil. But when I opens this link in Safari of My Mac it display me the Image.

I am using ..

NSString *str = @"http://chart.apis.google.com/chart?chs=150x150&cht=qr&chld=L|0&chl=http://MyServer.com/shareMyCard.php?value=1304057103";
NSURL *url = [NSURL URLWithString:str];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [UIImage imageWithData:data];

I don't know why the URL is Nil. I think because of query string in my string.

Any Idea how to get data from this Url String.

Thanks

like image 742
Kapil Choubisa Avatar asked Apr 30 '11 05:04

Kapil Choubisa


1 Answers

Your URL is nil because it contains special chars, use this following function to encode your url parameters before using them in URL -

-(NSString *) URLEncodeString:(NSString *) str
{

    NSMutableString *tempStr = [NSMutableString stringWithString:str];
    [tempStr replaceOccurrencesOfString:@" " withString:@"+" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [tempStr length])];


    return [[NSString stringWithFormat:@"%@",tempStr] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}
like image 88
Saurabh Avatar answered Sep 30 '22 05:09

Saurabh