Replace occurrences of space in URL
Asked Answered
D

12

62

I have a URL in an iPhone application to work with. But the problem is that it has some spaces in the URL. I want to replace the spaces with '%20'. I know that there are the stringByReplacingOccurencesOfString and stringByAddingPercentEscapesUsingEncoding methods. I also have used them. But they are not working for me. The spaces are replaced by some unusual values.

I'm applying those methods on an instance of NSString.

Damiendamietta answered 9/8, 2010 at 12:13 Comment(1)
Check out this post here: #696411 The Answer: NSString* escapedUrl = [originalUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];Stillmann
M
171

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]];
Mentality answered 4/3, 2011 at 9:55 Comment(5)
@RaquibulIslam I edited my answer , please check nowMentality
I think stringByReplacingPercentEscapesUsingEncoding() is deprecated. Instead, we can use stringByRemovingPercentEncodingBooklover
will it work for local path? i mean for documents dirGuttersnipe
@Guttersnipe I don't think you need to format path for local document dirMentality
If you use this funcion in a URL that is already encoded, it will not work. Must be carefull.Cryptography
T
9

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
Thayne answered 20/10, 2015 at 5:20 Comment(0)
C
6

To replace occurence in SWIFT 3 :

let updatedUrl = originalUrl.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)
Callable answered 27/6, 2017 at 8:13 Comment(1)
will it work for local path? i mean for documents dirGuttersnipe
C
5

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'

Chapell answered 8/2, 2017 at 20:15 Comment(6)
error : Value of type 'String' has no member 'trim'Quadrat
@Mehdico that is odd, I always trim my strings. At this example you don’t have to trim the string since you know what it is. But I’d clean the project and try to run it again. at the end of the string add .trimmedChapell
dude i think you use an extension for String class, because .trimmed is not found in swift 4 and 4.2Quadrat
You don’t have to trim the string in order to replace white spaceChapell
Try this for encoding :- stringByAddingPercentEncodingWithAllowedCharacters: URLPathAllowedCharacterSet and for decoding :- [NSURL fileURLWithPath:[self.yourString stringByRemovingPercentEncoding]]Phenomenon
will it work for local path? i mean for documents dirGuttersnipe
P
3

Swift 5

var urlString = originalString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
Paedogenesis answered 30/4, 2019 at 7:46 Comment(1)
will it work for local path? i mean for documents dirGuttersnipe
F
2

The quickest solution: just use the stringy method...

.replacingOccurrences(of: " ", with: "%20")

...at the end of your string, and it will do as it says.

Apple should be EMBARRASSED that their URL(string: ) method doesn't automatically do this (and more). It's 2023 and I wasted 3 hours finding this half-assed solution.

My specific example was inside cellForItemAt and having to do with optionals.

let stringOfImageURLFromFirebase = wordController?.word?.images[indexPath.item].imgUrl

let stringWithNoSpaces = string?.replacingOccurrences(of: " ", with: "%20")

if let imageURLString = stringWithNoSpaces,
   let imageURL = URL(string: imageURLString) {
         cell.definitionImageView.loadImageFromFirebase(url: imageURL)
    } else {
        cell.definitionImageView.image = UIImage(named: "slictionarylogo")
    }

You can fuddle with .addingPercentEncoding for a long time, try NSURL nonsense, and you'll just be faster with using the obvious. Apple sucks, and should've made this painfully easy since it's such a common problem. Again, they are asleep at the wheel, and their documentation is AWFUL too.

Fleuron answered 25/1, 2023 at 2:4 Comment(0)
G
0
var urlString :String = originalUrl.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)!
Gruchot answered 12/6, 2018 at 3:16 Comment(1)
You need to give more of an explanation to this code. There are others coming to this question looking for understanding not just code. Help others as well.Irra
P
0

Hope this will work

let url = "https:youtube.56432fgrtxcvfname=xyz&sname=tuv"
let urlNew:String = url.replacingOccurrences(of: " ", with: "%20")
Alamofire.request(urlNew, method: .get, headers: headers).responseJSON{
response in
print(response)    
}

It will remove all kind of spaces from the url.

Polygraph answered 26/9, 2019 at 22:41 Comment(0)
M
0

Swift 5.3, clear space your string,

let str = "  www.test.com  "
let trimmed = str.trimmingCharacters(in: .whitespacesAndNewlines)
print(str) // "www.test.com" 
Mustee answered 19/6, 2020 at 20:51 Comment(0)
W
-1

SWIFT 3.1

Simple way to replace an empty space with replacingOccurrences:

URL = URL.replacingOccurrences(of: " ", with: "", options: .literal, range: nil)
Winfordwinfred answered 17/8, 2017 at 10:4 Comment(1)
Doesn't work as URL has no member 'replacingOccurences'. String has that method but URL doesn't.Trinatrinal
M
-1

Swift 4, iOS-9

let **urlSearchVal**:String = "top 10 movies"     
let urlString = 

    "https://www.googleapis.com/youtube/v3/search?part=snippet&q=\(urlSearchVal)&key=......&type=video"   
//replace ...... above with your youtube key   
// to ignoring white space in search  
        let UrlString :String = urlString.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)!
Myatt answered 5/11, 2017 at 1:38 Comment(1)
welcome to SO. please improve the quality of you answerSuicide
B
-1

A Swift 4 solution. You simply pass through a string and it fills spaces with %20 and adds "http://" to the beginning to the string. Pretty sweet!

URL(fileURLWithPath: String) 
Baptistery answered 11/3, 2019 at 12:49 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.