Mejdi Lassidi
Mejdi Lassidi

Reputation: 999

Create NSURL with string containing "^" character gives a nil

When i try to creating an NSURL with a String containing "^" character the app crashs and the console says:

fatal error: unexpectedly found nil while unwrapping an Optional value

does any faced this before ?

EDIT:

It seems that the NSURL initializer gives a nil object, and the app crashs when trying to enforce unwrapping it.

how can i avoid getting this nil instance of NSURL with String containing such character?

EDIT

Here is some code, to clarify things:

let searchMethod = "advancedsearch.php?"
let searchParameters = "q=title:Book^100%20OR%20description:Book^15%20OR%20collection:Book^10%20OR%20language:Book^10%20OR%20text:Book^1&mediatype:texts+AND+NOT+hidden:true+AND+collection:texts&sort%5B%5D=titleSorter+asc&rows=10&output=json&start=1"
NSURL(string:"\(baseURL)/\(searchMethod)\(searchParameters)")
print("url \(url)")

The NSURL is nil,console gives :

url nil

Upvotes: 0

Views: 178

Answers (1)

shpasta
shpasta

Reputation: 1933

"^" symbol is not allowed for URL encoding.
Use this one for swift:

let encodedURLString = urlString.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())

Or for Objective-C:

NSString *encodedURLString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];

Upvotes: 0

Related Questions