Reputation: 961
Sorry for my dummy question but I'm new on Swift development, I have a project on Swift 1.1 which was working properly but after upgrading to Xcode to 7.3.1 (With Xcode 2.2.1) my project is built successfully but I'm getting an error while running it (on the let request line) with the following code:
// Send HTTP GET Request
let request = NSURLRequest(URL: NSURL(string: "http://11.22.33.44:8080/MySRV/login?email=\(emailField.text)&password=\(pwdField.text)")!)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{
(response: NSURLResponse?, data: NSData?, error: NSError?)-> Void in
print("response \(response?.description)")
the error is:
Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) fatal error: unexpectedly found nil while unwrapping an Optional value
I can imagine that my let request is nil but I don't know how to solve it.
Thanks for your help.
Upvotes: 0
Views: 1931
Reputation: 437392
The problem is likely a result of the fact that the text
properties of your two text fields are optionals, and thus is being added to your URL as Optional("[email protected]")
and Optional("password")
, and thus the attempt to build the URL is failing.
You can do something like:
guard let email = emailField.text else {
print("email is `nil`")
return
}
guard let password = pwdField.text else {
print("password is `nil`")
return
}
let request = NSURLRequest(URL: NSURL(string: "http://11.22.33.44:8080/MySRV/login?email=\(email)&password=\(password)")!)
Upvotes: 0
Reputation: 880
From here it looks like your unwrapping an optional value that is nil. Try this:
if let url: NSURL = NSURL(string: "http://11.22.33.44:8080/MySRV/login?email=\(emailField.text)&password=\(pwdField.text)") {
let request = NSURLRequest(URL: url)
// Do asynchronous request here
} else {
// NSURL is incorrect
}
This is how you can safely unwrap an optional value in Swift. You might also want to check if the emailField.text and pwdField.text are also not nil values. It would look something like this:
if let email: String = emailField.text {
// Text is not nil
} else {
// UITextField text is nil!
}
In the else blocks you can add logic to notify the user to input text or to perform some other action. You can read more about this here.
Hope this helps!
Upvotes: 3