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

前端 未结 4 838
感情败类
感情败类 2020-12-11 07:59

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

相关标签:
4条回答
  • 2020-12-11 08:20

    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];
    
    0 讨论(0)
  • 2020-12-11 08:28

    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.

    0 讨论(0)
  • 2020-12-11 08:33

    Yes there is, you need -stringByAddingPercentEscapesUsingEncoding: method:

    [NSURL URLWithString:[string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    
    0 讨论(0)
  • 2020-12-11 08:42
    + (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)

    0 讨论(0)
提交回复
热议问题