Search code examples
swiftnsurlnsurlrequest

NSURL nil when unwrapping an optional value | character not working?


let urlstr = "http://api.themoviedb.org/3/discover/movie?api_key={key}&with_genres=28|27|80|12|53|10752&sort_by=popularity.desc&page=\(pageNum)"

string looks like this:

http://api.themoviedb.org/3/discover/movie?api_key={key}&with_genres=28|27|80|12|53|10752&sort_by=popularity.desc&page=1

and works fine when I copy and paste in browser but when I try to create a NSURL it returns nil

let url = NSURL(string: urlstr)

I tried to erase | from the string and that actually worked, but i need that for my request so I can't do that, is there any way past this?


Solution

  • The "way past this" is to supply a legal URL string. Yours is illegal, because of the pipe characters - as you have rightly deduced - so you are going to get a nil result from NSURL(string: urlstr).

    Simply replace all those pipes by the equivalent percent-escape sequence and all will be well. You can get NSURL to help you by calling NSURL(scheme:host:path:) instead.