Space in query string of a URL Making it nil

Viewed 6406

I am working on a Swift 3.0 app, in which I am making a rest api call. The problem is that there may be a space in query string parameter, which is causing the URL to become nil. It works fine when there is no space in that parameter. But with a space it does not work.

Any help is appreciated.

Thanks

3 Answers

Ideally you'd be able to use URLQueryItem as in the answer above but I've never seen it replace spaces correctly. You can try this code in a newly created project to see what happens (Swift 4):

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // first example
    var components = URLComponents(string: "http://www.whatever.com/foo")!

    components.queryItems = [URLQueryItem(name: "feh", value: "feh"), URLQueryItem(name: "blah", value: "blah blah")]
    NSLog("\(components.url!)")

    // second example
    components = URLComponents(string: "http://www.whatever.com/foo")!

    components.queryItems = [URLQueryItem(name: "feh", value: "feh"), URLQueryItem(name: "blah", value: "blah blah"), URLQueryItem(name: "var with spaces", value: "here is a longer string with spaces in it")]
    NSLog("url=\(components.url!)")
    NSLog("string=\(components.string!)")
    NSLog("\(components.queryItems!)")
    NSLog("\(components.query!)")

    return true
}

This returns

2017-09-25 22:57:13.277885-0500 Bug29554407[10899:7054940] http://www.whatever.com/foo?feh=feh&blah=blah2lah

2017-09-25 22:57:13.278234-0500 Bug29554407[10899:7054940] url=http://www.whatever.com/foo?feh=feh&blah=blah2lah&var2ith(null)paces=here 0s 0x0p+0 0nger(null)tring2ith(null)paces 0n 0t

2017-09-25 22:57:13.278359-0500 Bug29554407[10899:7054940] string=http://www.whatever.com/foo?feh=feh&blah=blah2lah&var2ith(null)paces=here 0s 0x0p+0 0nger(null)tring2ith(null)paces 0n 309458872t

2017-09-25 22:57:13.280232-0500 Bug29554407[10899:7054940] [feh=feh, blah=blah blah, var with spaces=here is a longer string with spaces in it]

2017-09-25 22:57:13.280334-0500 Bug29554407[10899:7054940] feh=feh&blah=blah blah&var with spaces=here is a longer string with spaces in it

I wonder if there is some sort of Swift/Objc difference between strings because the problem doesn't happen when using Objective-C.

Related