Objective-c – NSURL URLWithString:theString returns Nil

iphonensurlobjective c

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

Best Answer

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];
}
Related Topic