Swift3.0语言教程使用URL字符串

    xiaoxiao2021-11-07  77

    Swift3.0语言教程使用URL字符串

    Swift3.0语言教程使用URL字符串,和路径一样,URL其实也是字符串,我们可以将这些字符串称为URL字符串。本小节将讲解URL字符串的使用。

    1.编码

    现在的网络存在很多的泄漏信息的危险,为了解决这一危险,URL字符串提供了编码的的方式,在NSString中开发者可以使用addingPercentEncoding(withAllowedCharacters:)方法实现编码的功能,也就是将指定的字符集使用“%”代替,其语法形式如下:

    func addingPercentEncoding(withAllowedCharacters allowedCharacters: CharacterSet) -> String?

    其中,allowedCharacters用来指定进行编码的字符集,这些字符串集会使用%代替。

    【示例1-96】以下将使用addingPercentEncoding(withAllowedCharacters:)方法对URL字符串进行编码。

    import Foundation

    var path=NSString(string:"https://www.xiaocaobank.com")

    var cs=NSCharacterSet(charactersIn:"`#%^{}\"[]|\\<>//").inverted

    print(path.addingPercentEncoding(withAllowedCharacters: cs)!)                            //编码

    运行结果如下:

    https://www.xiaocaobank.com

    2.解码

    在NSString中有编码的方法就会存在有解码的方法,要实现解码功能,需要使用到removingPercentEncoding属性,它可以将“%”去除,其语法形式如下:

    var removingPercentEncoding: String? { get }

    【示例1-97】以下将对编码的URL字符串进行解码。

    import Foundation

    var path=NSString(string:"http://hogehoge.com/?param=!*'();:@&=+$,/?%#[]")

    var cs=NSCharacterSet.alphanumerics

    var encodePath=path.addingPercentEncoding(withAllowedCharacters: cs)!

    print(encodePath)

    var decodeString=encodePath.removingPercentEncoding                                        //解码

    print(decodeString!)

    运行结果如下:

    http://hogehoge.com/?param=!*'();:@&=+$,/?%#[]

    http://hogehoge.com/?param=!*'();:@&=+$,/?%#[]

    Swift3.0语言教程使用URL字符串

    相关阅读:Swift3.0语言教程使用路径字符串 

    转载请注明原文地址: https://ju.6miu.com/read-678088.html

    最新回复(0)