0

I already tried many many examples found here, but none of then works... the url is always nil ..

here the String :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
        }

Should i decode and then encode again?

Already tried this Solution, but dont work, the NSURL initialization is always nil

Community
  • 1
  • 1
Vinícius Albino
  • 527
  • 1
  • 7
  • 23
  • You have to explicitly allow `http://` URLs (as opposed to `https://`). Have you done this? And are you receiving any error messages? – Ike10 Jun 16 '16 at 20:12
  • Sure, another requests works fine, but just some, with this encoding doesnt work – Vinícius Albino Jun 16 '16 at 20:14
  • I don't believe the initializer for `NSURL` returns an optional. Try removing the guard statement. Your `nil` coalescing may be setting the value to an empty string. – Ike10 Jun 16 '16 at 20:20
  • @Ike10 the value for NSURL is always nil, if i dont use guard the request has no url.. – Vinícius Albino Jun 16 '16 at 20:24
  • Can you post some more code to give this code context? Like where it is and how the `urlSet` is determined? – Ike10 Jun 16 '16 at 20:28

2 Answers2

0

This code solved my problem :

extension String {
    func encodeString() -> String {
        let URLCombinedCharacterSet = NSMutableCharacterSet()
        URLCombinedCharacterSet.formUnionWithCharacterSet(.URLQueryAllowedCharacterSet())
        URLCombinedCharacterSet.addCharactersInString("@#&=*+-_.,:!?()/~'%")
        let urlEncoded = self.stringByAddingPercentEncodingWithAllowedCharacters(URLCombinedCharacterSet)
        return urlEncoded ?? self
    }
}
Vinícius Albino
  • 527
  • 1
  • 7
  • 23
0

| is not a valid character in the URL string. You need to escape it:

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!
Code Different
  • 90,614
  • 16
  • 144
  • 163