user3900721
user3900721

Reputation:

sendSynchronousRequest error in unwrapping on device, works in emulator

The following line works perfectly fine in the emulator, but not on the actual device. It gives me the error: fatal error: unexpectedly found nil while unwrapping an Optional value

var urlData:NSData = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&error)!

The original in another project did not have the ! at the end, and it worked 100% in beta5, now in beta6, it throws an error unless I put it in. It still works in the emulator, but not on my iPhone?

Any ideas?

Upvotes: 1

Views: 188

Answers (1)

Antonio
Antonio

Reputation: 72760

I think there must be something wrong in your app when you run in the device (such as the URL/IP it connects to).

If it throws that error, that means sendSynchronousRequest returns nil. My advice is to:

  • make urlData optional var urlData: NSData? = ..., and check later if it has a value or not
  • check that the server you are connecting to, and/or the parameters in the request, are correct

It's very important that you don't use forced unwrapping on a value that can be nil. That always generates a runtime error, so I would consider it a bad practice. You should limit forced unwrapping to cases where you are 100% sure the optional has a value, such as when you have explicitly checked for that without using optional binding.

As for the server/request check, I often make requests to a local development server when I am running in the simulator, and a production or staging remote server when using a device. Maybe you're doing something similar in your code.

Upvotes: 1

Related Questions