iOS : How to do proper URL encoding?

后端 未结 10 1927
一整个雨季
一整个雨季 2020-12-13 19:20

I\'m unable to open a URL into UIWebView so I\'ve seached & found that I need to encode URL, so I tried to encode it but, I\'ve facing problem in URL encodi

10条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-13 19:33

    I did some tests and I think the problem is not really with the UIWebView but instead that NSURL won't accept the URL because of the é in "Témp" is not encoded properly. This will cause +[NSURLRequest requestWithURL:] and -[NSURL URLWithString:] to return nil as the string contains a malformed URL. I guess that you then end up using a nil request with -[UIViewWeb loadRequest:] which is no good.

    Example:

    NSLog(@"URL with é: %@", [NSURL URLWithString:@"http://host/Témp"]);
    NSLog(@"URL with encoded é: %@", [NSURL URLWithString:@"http://host/T%C3%A9mp"]);
    

    Output:

    2012-10-02 12:02:56.366 test[73164:c07] URL with é: (null)
    2012-10-02 12:02:56.368 test[73164:c07] URL with encoded é: http://host/T%C3%A9mp
    

    If you really really want to borrow the graceful handling of malformed URLs that WebKit has and don't want to implement it yourself you can do something like this but it is very ugly:

    UIWebView *webView = [[[UIWebView alloc]
                           initWithFrame:self.view.frame]
                          autorelease];
    
    NSString *url = @"http://www.httpdump.com/texis/browserinfo/Témp.html";
    
    [webView loadHTMLString:[NSString stringWithFormat:
                             @"",
                             [[[NSString alloc]
                               initWithData:[NSJSONSerialization
                                             dataWithJSONObject:url
                                             options:NSJSONReadingAllowFragments
                                             error:NULL]
                               encoding:NSUTF8StringEncoding]
                              autorelease]]
                    baseURL:nil];
    

提交回复
热议问题