Replace occurrences of space in URL

Swift 2.0

let originalUrl = "http://myurl.com/my photo.png"
let urlNew:String = urlReq.stringByAddingPercentEncodingWithAllowedCharacters( NSCharacterSet.URLQueryAllowedCharacterSet())! 

Output:

http://myurl.com/my%20photo.png

To replace occurence in SWIFT 3 :

let updatedUrl = originalUrl.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)

Swift 4

Another way to replace an empty space with replacingOccurrences method:

let yourString = "http://myurl.com/my photo.png"
let urlNew:String = yourString.replacingOccurrences(of: " ", with: "%20").trimmed 

That will replace the empty space (" ") with '%20'


The correct format for replacing space from url is :

Swift 4.2 , Swift 5

var urlString = originalString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)

Swift 4

var urlString = originalString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)

Objective C

NSString *urlString;//your url string.

urlString = [originalUrl stringByReplacingOccurrencesOfString:@" " withString:@"%20"];

or

urlString = [originalUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

iOS 9 and later

urlString = [originalUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];