Replacement for stringByAddingPercentEscapesUsingEncoding in ios9?

后端 未结 8 1587
耶瑟儿~
耶瑟儿~ 2020-11-29 01:09

In iOS8 and prior I can use:

NSString *str = ...; // some URL
NSString *result = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
         


        
8条回答
  •  鱼传尺愫
    2020-11-29 01:29

    The deprecation message says (emphasis mine):

    Use stringByAddingPercentEncodingWithAllowedCharacters(_:) instead, which always uses the recommended UTF-8 encoding, and which encodes for a specific URL component or subcomponent since each URL component or subcomponent has different rules for what characters are valid.

    So you only need to supply an adequate NSCharacterSet as argument. Luckily, for URLs there's a very handy class method called URLHostAllowedCharacterSet that you can use like this:

    let encodedHost = unencodedHost.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
    

    Update for Swift 3 -- the method becomes the static property urlHostAllowed:

    let encodedHost = unencodedHost.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
    

    Be aware, though, that:

    This method is intended to percent-encode an URL component or subcomponent string, NOT an entire URL string.

提交回复
热议问题