如何正确编码URL字符串

时间:2016-06-16 20:09:13

标签: ios swift encoding ios9 nsurlrequest

我已经尝试了很多这里找到的例子,但是没有一个可以工作......网址总是零...

这里是字符串:http://www.tst.com.br/?Nr=OR(product.productType.displayName:Acess%C3%B3rios,product.productType.displayName:Outros%20Produtos)&Ns=sku.sortPriority|0&mi=hm_ger__mntop__FUT-outros_&cm_re=mntop-_-ger_-_-_FUT-outros_____&fc=menu&test=test

            let urlSet = "http://www.tst.com.br/?Nr=OR(product.productType.displayName:Acess%C3%B3rios,product.productType.displayName:Outros%20Produtos)&Ns=sku.sortPriority|0&mi=hm_ger__mntop__FUT-outros_&cm_re=mntop-_-ger_-_-_FUT-outros_____&fc=menu&test=test"
        guard let url = NSURL(string: urlSet ?? "") else {
            return
        }

我应该解码然后重新编码吗?

已经尝试了这个Solution,但是没有用,NSURL初始化总是为零

2 个答案:

答案 0 :(得分:0)

这段代码解决了我的问题:

extension String {
    func encodeString() -> String {
        let URLCombinedCharacterSet = NSMutableCharacterSet()
        URLCombinedCharacterSet.formUnionWithCharacterSet(.URLQueryAllowedCharacterSet())
        URLCombinedCharacterSet.addCharactersInString("@#&=*+-_.,:!?()/~'%")
        let urlEncoded = self.stringByAddingPercentEncodingWithAllowedCharacters(URLCombinedCharacterSet)
        return urlEncoded ?? self
    }
}

答案 1 :(得分:0)

|不是URL字符串中的有效字符。你需要逃脱它:

let query = "Nr=OR(product.productType.displayName:Acess%C3%B3rios,product.productType.displayName:Outros%20Produtos)&Ns=sku.sortPriority|0&mi=hm_ger__mntop__FUT-outros_&cm_re=mntop-_-ger_-_-_FUT-outros_____&fc=menu&test=test"

let components = NSURLComponents()
components.scheme = "http"
components.host = "www.tst.com.br"
components.path = "/"
components.query = query.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())

let url = components.URL!