iOS : How to do proper URL encoding?

后端 未结 10 1880
一整个雨季
一整个雨季 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:21

    Swift 4.x

    let originalString = "https://www.somedomain.com/folder/some cool file.jpg"
    let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
    print(escapedString!)
    
    0 讨论(0)
  • 2020-12-13 19:22

    The answer @Dhaval Vaishnani provided is only partially correct. This method treats the ?, = and & characters as not to be encoded, since they're valid in an URL. Thus, to encode an arbitrary string to be safely used as a part of an URL, you can't use this method. Instead you have to fall back to using CoreFoundation and CFURLRef:

    NSString *unsafeString = @"this &string= confuses ? the InTeRwEbZ";
    CFStringRef safeString = CFURLCreateStringByAddingPercentEscapes (
        NULL,
        (CFStringRef)unsafeString,
        NULL,
        CFSTR("/%&=?$#+-~@<>|\\*,.()[]{}^!"),
        kCFStringEncodingUTF8
    );
    

    Don't forget to dispose of the ownership of the resulting string using CFRelease(safeString);.

    Also, it seems that despite the title, OP is looking for decoding and not encoding a string. CFURLRef has another, similar function call to be used for that:

    NSString *escapedString = @"%32%65BCDEFGH";
    CFStringRef unescapedString = CFURLCreateStringByReplacingPercentEscapesUsingEncoding (
        NULL,
        (CFStringRef)escapedString,
        CFSTR(""),
        kCFStringEncodingUTF8
    );
    

    Again, don't forget proper memory management.

    0 讨论(0)
  • 2020-12-13 19: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.

    0 讨论(0)
  • 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:
                             @"<script>window.location=%@;</script>",
                             [[[NSString alloc]
                               initWithData:[NSJSONSerialization
                                             dataWithJSONObject:url
                                             options:NSJSONReadingAllowFragments
                                             error:NULL]
                               encoding:NSUTF8StringEncoding]
                              autorelease]]
                    baseURL:nil];
    
    0 讨论(0)
  • 2020-12-13 19:34

    You probably need to break the URL down into it's constituent parts and then URL encode the host and path but not the scheme. Then put it back together again.

    Create an NSURL with the string and then use the methods on it such as host, scheme, path, query, etc to pull it apart. Then use CFURLCreateStringByAddingPercentEscapes to encode the parts and then you can put them back together again into a new NSURL.

    0 讨论(0)
  • 2020-12-13 19:38

    It's very simple to encode the URL in iPhone. It is as following

    NSString* strURL = @"http://somedomain.com/data/Témp Page - Open.html";
    
    NSURL* url = [NSURL URLWithString:[strURL stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    

    It's a perfect way to encode the URL, I am using it and it's perfectly work with me.

    Hope it will help you!!!

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