Reputation: 739
I am trying to implement error handling as explained in the 'Error Reporting' section of Apple's Swift Docs (https://developer.apple.com/library/mac/documentation/swift/conceptual/BuildingCocoaApps/AdoptingCocoaDesignPatterns.html) but I must be missing something.
I have the code below (simplified), and even if the network request clearly fails (I am disconnected from the internet, and "ERROR" gets printed) the error variable I pass as a pointer is always nil inside the completion block...
What am I doing wrong? Thanks!
override func viewDidLoad() {
super.viewDidLoad()
var error: NSError?
// THIS IS ACTUALLY IN ANOTHER CLASS,
// BUT EVEN IF PLACED IN THE SAME CLASS I STILL GET THE SAME PROBLEM
doStuff({ (result) -> Void in
println("\(error)") // THIS PRINTS NIL
}, errorPointer: &error)
}
func doStuff(completion: (result:SomeType) -> Void, errorPointer: NSErrorPointer) {
// SETUP CODE NOT INCLUDED
let downloadTask = manager.downloadTaskWithRequest(req, progress: nil, destination: { (url, response) -> NSURL! in
return destinationURL
}) { (response, url, error) -> Void in
// CREATE RESULT
if(error != nil && errorPointer != nil) {
println(“ERROR”) // THIS GETS PRINTED
errorPointer.memory = error // ALSO TRIED NSError(...)
}
completion(result)
}
downloadTask.resume()
}
Upvotes: 2
Views: 2006
Reputation: 13181
Solution
You will find a clear example of Swift error handling in the free ebook from Apple entitled Using Swift with Cocoa and Objective-C (p.51).
var writeError: NSError?
let written = myString.writeToFile(path, atomically: false,
encoding: NSUTF8StringEncoding,
error: &writeError)
if !written {
if let error = writeError {
println("write failure: \(error.localizedDescription)")
}
}
Excerpt From: Apple Inc. “Using Swift with Cocoa and Objective-C.” iBooks. https://itun.es/us/1u3-0.l
Basically you want to look at the memory address of the error and then test that value to handle the error. Try extrapolating from this and rewrite your code to achieve the effective results.
Also if you must use NSErrorPointer then see the following SO question and answer.
Upvotes: 1