0

I am using following code to encode my string url

let originalString = "test/test"
let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: . urlQueryAllowed)
print(escapedString!)

I am looking for Swift extension to encode url so that I don't have to write code every time. How to create extension to encode url

amodkanthe
  • 4,345
  • 6
  • 36
  • 77

2 Answers2

3

If you want to create an extension you just need to add

extension YourViewController {
    func stringEncode(encodedString: String) {
        let escapedString = 
        encodedString.addingPercentEncoding(with(withAllowedCharacters: .urlHostAllowed)
     print (escapedString!)
   }
}

Then call that function wherever you want to use it. Then just pass the string through the encodedString portion of the function. Like if you were going to use it on a button press to encode something from a textField:

@IBOutlet weak var textField: UITextField!

@IBAction func buttonPressed (_ sender: Any) {
    stringEncode(encodedString: textField.text)
}

Then on the button press it should perform the function you want. I'm still learning Swift myself, but I thought I would try to answer- let me know if that works!

Frank Foster
  • 139
  • 9
  • not working got url like this https%3A%2F%2Ftximages.apk.in%2test2%2Fretailer%2F320%2Fss%20_Point-6685.jpg – amodkanthe Dec 18 '19 at 20:01
  • That's because : and / are not expected in URL hosts (see [`.urlHostAllowed`](https://developer.apple.com/documentation/foundation/characterset/1780202-urlhostallowed)). You should only encode the parts you need to encode. – shim Dec 18 '19 at 20:02
  • i dont have base url and these urls are dynamic coming from server I am using them to load images so will have to encode entire url – amodkanthe Dec 18 '19 at 20:11
1

I think you can do something like this:

extension String {
    var encoded: String? {
        return self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
    }
}

and call it like:

let encodedUrl = "http://...".encoded
Claudio
  • 5,078
  • 1
  • 22
  • 33