60

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Joy
  • 1,609
  • 3
  • 16
  • 28
  • 3
    Check out this post here: http://stackoverflow.com/questions/695911/question-about-character-of-nsstring-invalid-in-url-on-iphone The Answer: NSString* escapedUrl = [originalUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; – Tieme Jun 12 '11 at 18:23

12 Answers12

169

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]];
Raj
  • 5,895
  • 4
  • 27
  • 48
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
Dasoga
  • 5,489
  • 4
  • 33
  • 40
6

To replace occurence in SWIFT 3 :

let updatedUrl = originalUrl.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)
Amit
  • 4,837
  • 5
  • 31
  • 46
Jitendra Tanwar
  • 249
  • 2
  • 11
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'

Gilad Brunfman
  • 3,452
  • 1
  • 29
  • 29
  • error : Value of type 'String' has no member 'trim' – Sabrina Jan 17 '19 at 15:27
  • @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 *.trimmed* – Gilad Brunfman Jan 17 '19 at 15:37
  • dude i think you use an extension for String class, because .trimmed is not found in swift 4 and 4.2 – Sabrina Jan 18 '19 at 10:19
  • You don’t have to trim the string in order to replace white space – Gilad Brunfman Jan 18 '19 at 10:21
  • Try this for encoding :- stringByAddingPercentEncodingWithAllowedCharacters: URLPathAllowedCharacterSet and for decoding :- [NSURL fileURLWithPath:[self.yourString stringByRemovingPercentEncoding]] – Shrikant Phadke Mar 10 '20 at 05:00
  • will it work for local path? i mean for documents dir – guru Jun 25 '20 at 09:46
3

Swift 5

var urlString = originalString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
Shakeel Ahmed
  • 5,361
  • 1
  • 43
  • 34
1

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.

John Pitts
  • 653
  • 6
  • 17
0
var urlString :String = originalUrl.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)!
Sangram Shivankar
  • 3,535
  • 3
  • 26
  • 38
samaujs
  • 1
  • 3
  • 2
    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. – wesley franks Jun 25 '19 at 16:50
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.

Raghib Arshi
  • 717
  • 8
  • 12
0

Swift 5.3, clear space your string,

let str = "  www.test.com  "
let trimmed = str.trimmingCharacters(in: .whitespacesAndNewlines)
print(str) // "www.test.com" 
ikbal
  • 1,110
  • 12
  • 21
-1

SWIFT 3.1

Simple way to replace an empty space with replacingOccurrences:

URL = URL.replacingOccurrences(of: " ", with: "", options: .literal, range: nil)
MLavoie
  • 9,671
  • 41
  • 36
  • 56
  • Doesn't work as URL has no member 'replacingOccurences'. String has that method but URL doesn't. – shiv Sep 17 '19 at 21:42
-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)!
Cyber Progs
  • 3,656
  • 3
  • 30
  • 39
that guy
  • 193
  • 2
  • 8
-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) 
KDiaz
  • 37
  • 7