iOS : How to do proper URL encoding?

2020-02-08 04:07发布

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 encoding : My URL is http://somedomain.com/data/Témp%20Page%20-%20Open.html (It's not real URL).

I'm concerned with %20 that I tried to replace using stringByReplacingOccuranceOfString:@"" withString:@"" , it give me the URL I wanted like http://somedomain.com/data/Témp Page - Open.html However its not opening in UIWebView but amazingly it opens in Safari & FireFox perfect. Even I open unencoded URL its automatically converts and open the page I'm looking for.

I've google for URL encoding & it points me to different results I already checked but no results help me out!! I tried different functions answers in different URL encoding question but it just changed all special characters and make my URL like, http%3A%2F%2Fsomedomain.com%2Fdata%2FT... which can't open in UIWebView and even in any browser.

It gives the following Error Log in UIWebView delegate

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error { }

Error Code : 101 & Description : Error Domain=WebKitErrorDomain Code=101 "The operation couldn’t be completed. (WebKitErrorDomain error 101.)" UserInfo=0x6e4cf60 {}

10条回答
看我几分像从前
2楼-- · 2020-02-08 04:24

Swift 4.x

let originalString = "https://www.somedomain.com/folder/some cool file.jpg"
let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
print(escapedString!)
查看更多
【Aperson】
3楼-- · 2020-02-08 04:27

can you please Try this out.

    //yourURL contains your Encoded URL
    yourURL = [yourURL stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
    yourURL = [yourURL stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    NSLog(@"Keyword:%@ is this",yourURL);

I am not sure,but I have solved using this in my case. Hope this will solve yours.

查看更多
姐就是有狂的资本
4楼-- · 2020-02-08 04:30

This may useful to someone who's reach to this question for URL encoding, as my question likely different which has been solved and accepted, this is the way I used to do encoding,

-(NSString *)encodeURL:(NSString *)urlString
{
    CFStringRef newString = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)urlString, NULL, CFSTR("!*'();:@&=+@,/?#[]"), kCFStringEncodingUTF8);
    return (NSString *)CFBridgingRelease(newString);
}
查看更多
放荡不羁爱自由
5楼-- · 2020-02-08 04:38

I think this will work for you

[strUrl stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLQueryAllowedCharacterSet]

the Native method for URL Encoding.

查看更多
登录 后发表回答