I used this method very much in Swift 1.2: NSURLConnection.sendSynchronousRequest(:_:_:_)
but this is apparently deprecated in iOS9. It still works however but now it uses the new Swift 2.0 Error Handling and I don't know how I will get the error message if it fails, ex. if time runs out.
I know I have to put it into a do-catch and then say try before the metho but I dont know how to catch the error message.
do {
let data = try NSURLConnection.sendSynchronousRequest(request, returningResponse: nil)
return data
}
catch _ {
return nil
}
Before I used NSError and then its description property, but now I have no clue.
Overview. Any type that declares conformance to the Error protocol can be used to represent an error in Swift's error handling system. Because the Error protocol has no requirements of its own, you can declare conformance on any custom type you create.
Sometimes functions fail because they have bad input, or because something went wrong internally. Swift lets us throw errors from functions by marking them as throws before their return type, then using the throw keyword when something goes wrong.
According to the guides, Swift projects should declare custom error types to signal exceptional conditions (CustomErrorTypes). G-5 shows an example using a struct as an error type; G-1 to G-4 and G-6 recommend using enums as error types.
Use automatic error
variable, and you can cast it to NSError
if you wish:
catch {
let nsError = error as NSError
print(nsError.localizedDescription)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With