iosobjective-cnsstringnsurl

Replace occurrences of space in URL


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.


Solution

  • 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]];