Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift/https: NSURLSession/NSURLConnection HTTP load failed

Unfortunately this morning my XCode updated to version 7 and the iOS app I was developing with http now wants https. So, following many tutorials, I configured my MAMP server in order to use https/ssl creating a dummy certificate. Now in my iOS app URLs are like the following:

static var webServerLoginURL = "https://localhost:443/excogitoweb/mobile/loginM.php"
static var webServerGetUserTasks = "https://localhost:443/excogitoweb/mobile/handleTasks.php"
static var webServerGetUsers = "https://localhost:443/excogitoweb/mobile/handleUsers.php"
static var webServerGetProjects = "https://localhost:443/excogitoweb/mobile/handleProjects.php"

and they work fine if I try to access them in my browser. I was used to access the database and php files with NSURLSession.sharedSession().dataTaskWithRequest() which now raises the error in title. For example, here's the line where error is raised:

if let responseJSON: [[String: String]] = (try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions())) as? [[String: String]] {
...
}

and this is the complete error message:

2015-09-21 16:41:48.354 ExcogitoWeb[75200:476213] CFNetwork SSLHandshake failed (-9824)
2015-09-21 16:41:48.355 ExcogitoWeb[75200:476213] NSURLSession/NSURLConnection   HTTP load failed (kCFStreamErrorDomainSSL, -9824)
fatal error: unexpectedly found nil while unwrapping an Optional value

I would like to know how to fix this. I've read some useful answers here but there are many things I still don't understand and if anyone would help/explain me I'd be very grateful.

like image 528
SagittariusA Avatar asked Sep 21 '15 14:09

SagittariusA


2 Answers

Add this to your app's Info.plist

<key>NSAppTransportSecurity</key>  
    <dict>  
    <key>NSAllowsArbitraryLoads</key>  
    <true/>  
    </dict>
like image 70
mychar Avatar answered Sep 20 '22 21:09

mychar


fatal error: unexpectedly found nil while unwrapping an Optional value

usually means that you're doing something not so good, and by looking at your if

if let responseJSON: [[String: String]] = (try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions())) as? [[String: String]] {

I can see that there's a data!, but that data object is nil. You really should unwrap the optionals before using them, especially when working with remote data.

Then you have a network error, that's probably related to the ATS Apple added in iOS 9.

See another answer on how to temporarily disable ATS. https://stackoverflow.com/a/30748166/421755

edit: I see now that you added ssl to your localhost, that's good. However it's not enough for ATS to work, since it needs TLS 1.2 and not self-signed certificates.

like image 31
Simon Avatar answered Sep 19 '22 21:09

Simon