Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
912 views
in Technique[技术] by (71.8m points)

iphone - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...