How to prepare an NSURL from an NSString continaing international characters?

会有一股神秘感。 提交于 2019-11-28 12:37:43

Yes there is, you need -stringByAddingPercentEscapesUsingEncoding: method:

[NSURL URLWithString:[string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

This would ensure NSURL *url does not return nil because of the "|" in the urlString.

NSString *urlString = [[NSString stringWithFormat:@"http://api.service.com/Service.svc?sort=name|ascending"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSURL *url = [NSURL URLWithString:urlString];
fady

You can use NSURL directly without NSString:

//.h file

@interface NewsBrowser : UIViewController {
    UIWebView *webView;
    NSURL *NewsUrl;
}

@property (nonatomic, retain) IBOutlet UIWebView *webView;
@property (nonatomic, assign) NSURL *NewsUrl;

@end

//.m file

[webView loadRequest:[NSURLRequest requestWithURL:NewsUrl]];

Just pass a NSURL from another view (using NewsUrl variable) to this view.

+ (NSURL*) URLWithStringWithSpecialChars:(NSString *)sURL
{
    NSURL *url = [NSURL URLWithString:sURL];
    if(url == nil)
        return [NSURL URLWithString:[sURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    else
        return url;
}

calling this function instead of URLWithString: should ensure that a valid NSURL is always returned (instead of nil when needed)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!