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.
You can now throw any object inheriting
ErrorType
, and provide custom handling in thecatch
sentence. You can also cast the error toNSError
to accesslocalizedDescription
for handling third party errors.Casting an enum
ErrorType
will produce aNSError
withdomain
equal to the enum name,code
equal to the enum value and an auto-generatedlocalizedDescription
with the following format:For example, the following code:
Will print
Use automatic
error
variable, and you can cast it toNSError
if you wish:Despite the question title specifying Swift 2, this answer is for Swift 3.
As @redent84 points out, since Swift 2 an Error object may be a home-made one. Here's a method I wrote to analyze and print the default error object available in a "catch" statement that doesn't specify any specific error type:
Then you can call it like this: