How to prepare an NSURL from an NSString continain

2020-02-06 10:02发布

I have to access a web server using a GET with international characters (Hebrew in my case but could be anything). So I make an NSString just fine but

[NSURL URLWithString:urlString]; // returns nil.

I realize I probably have to convert the international characters to percent codes.

Is there a built in method in Objective-c to do so?

4条回答
太酷不给撩
2楼-- · 2020-02-06 10:06

Yes there is, you need -stringByAddingPercentEscapesUsingEncoding: method:

[NSURL URLWithString:[string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
查看更多
你好瞎i
3楼-- · 2020-02-06 10:08

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.

查看更多
一纸荒年 Trace。
4楼-- · 2020-02-06 10:15

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];
查看更多
爷的心禁止访问
5楼-- · 2020-02-06 10:30
+ (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)

查看更多
登录 后发表回答