Unit Testing a method that uses REST calls in Swift - json

Let me start out by stating I'm still unfamiliar with what I'm trying to do, but striving to get better!
I'm working on a project that I'm writing unit tests for and I'm having some trouble with how to approach the problem.
The method I'm testing utilizes a RESTAPI call to verify a users credentials. I'm not sure what the best way to unit test would be.
Here is the method I'm looking to make the Unit test for:
#IBAction func loginBtnActivate(sender: UIButton) {
let enteredEmail: String = emailField.text!
let enteredPassword: String = passwordField.text!
let testInfo:[String: AnyObject] = ["User": enteredEmail, "Password": enteredPassword]
RestApiManager.sharedInstance.postLogin(testInfo) { (json, statusCode) in
if statusCode == 200 {
let AuthToken: TokenObject = (TokenObject(json: json))
try! self.keychain.set(AuthToken.Authorization, key:"Authorization")
try! self.keychain.set(AuthToken.LifeTime, key: "LifeTime")
try! self.keychain.set(AuthToken.UUID, key: "UUID")
NSOperationQueue.mainQueue().addOperationWithBlock {
self.performSegueWithIdentifier("loginToMyHealth", sender: nil)
}
} else if statusCode == 401 {
self.incorrectLoginAlert()
} else if statusCode == 503 {
print("Service Unavailable Please Try Again Later")
}
}
}
This is currently the approach I'm taking:
func testLoginInfoMatchesDataOnServer(){
let enteredEmail: String = "user"
let enteredPassword: String = "password"
let testInfo:[String: AnyObject] = ["User": enteredEmail, "Password": enteredPassword]
RestApiManager.sharedInstance.postLogin(testInfo) { (json, statusCode) in
XCTAssert(statusCode == 200, "statusCode is not matching the server data")
}
I'm simply verifying that the Rest call is successful and that the credentials are matching the JSON. The XCTAssert call doesn't appear to be working correctly. No matter what I put as the first parameter, XCTAssert doesn't affect whether the test is successful or not.
Example, if I put:
XCTAssert(false, "statusCode is not matching the server data")
The test will still pass regardless of what I put. If I place the Assert function outside the brackets then it appears the variable "statusCode" is out of scope so I'm stuck with a
Use of unresolved identifier 'statusCode'.
func testLoginInfoMatchesDataOnServer(){
let enteredEmail: String = "user"
let enteredPassword: String = "password"
let testInfo:[String: AnyObject] = ["User": enteredEmail, "Password": enteredPassword]
RestApiManager.sharedInstance.postLogin(testInfo) { (json, statusCode) in
}
XCTAssert(statusCode == 200, "statusCode is not matching the server data")
}
I was looking at this guide for help.. Would this be a better approach for what I'm trying to do?
http://roadfiresoftware.com/2016/06/how-do-you-unit-test-rest-calls-in-swift/
Again my understanding of some core concepts might be entirely off so I really appreciate your advice here!
Thanks in advance!
Sean W.

First Few problems with your code
function test(){
RestApiManager.sharedInstance.postLogin(testInfo) { (json, statusCode) in
}//PostLogin call ends
XCTAssert(statusCode == 200, "statusCode is not matching the server data") // Here StatusCode is not accessible as outside the block
}// end function
If you want to use Status Code you should do
function test(){
RestApiManager.sharedInstance.postLogin(testInfo) { (json, statusCode) in
XCTAssert(statusCode == 200, "statusCode is not matching the server data") // Here StatusCode is accessible inside the block
}//PostLogin call ends
}// end function
But this will fail since you need to wait for the response. That can be done using
waitForExpectationsWithTimeout(5)
So proper way to call this would be --
function test(){
let URL = NSURL(string: "http://google.com/")!
let expectation = expectationWithDescription("GET \(URL)")
RestApiManager.sharedInstance.postLogin(testInfo) { (json, statusCode) in
XCTAssert(statusCode == 200, "statusCode is not matching the server data") // Here StatusCode is accessible inside the block
expectation.fulfill()
}//PostLogin call ends
waitForExpectationsWithTimeout(5){ error in
if let error = error {
print("Error: \(error.localizedDescription)")
}
}//Wait block end
}// end function
Important lines here are
expectation.fulfill() // tells process is complete
and
waitForExpectationsWithTimeout(5){} //tells wait for 5secs or throw error
For more info

Related

Swift - Different output based on JSON response contents

This question will probably come off as very basic, and something that probably can be found through searching, but despite my efforts of searching StackOverflow and just google I can't find any up-to-date thread or post regarding how to handle the different responses of a REST API, and, as I've found out, having an up-to-date thread is important to save trouble down the road when errors occur. So, to jump into it, I have an API endpoint on my server for logging in. It responds, as one would assume, with either two cases given login credentials;
If the login information succeeds, it returns this JSON Object:
{
"user": {
"id": 1,
"type": "user",
"name": "username",
"api_token": "accesstokenhere"
},
"access_token": "accesstokenhere"
}
If it doesn't succeed, it gives this response
{
"message": "Invalid credentials"
}
Now I have the login screen for my app, upon pressing "log in", submit the information to the server and get this response back, which is not of issue and very well documented. I have the following code so far:
import SwiftUI
import Combine
import Foundation
public struct UserModel: Decodable {
let id: Int
let username: String
let age: Int
enum CodingKeys: String, CodingKey {
case id = "id"
case username = "name"
case age = "age"
}
}
public struct UserResponse: Decodable {
public let user: UserModel
public let accessToken: String
enum CodingKeys: String, CodingKey {
case user = "user"
case accessToken = "access_token"
}
}
public class UserFetcher: ObservableObject {
public let objectWillChange = PassthroughSubject<UserFetcher,Never>()
#Published var hasFinished: Bool = false {
didSet {
objectWillChange.send(self)
}
}
var user: UserResponse?
#Published var incorrectLogin: Bool = false {
didSet {
objectWillChange.send(self)
}
}
init(){
guard let url = URL(string: "https://mywebsite.com/api/login") else { return }
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
do {
if let d = data {
let decodedRes = try JSONDecoder().decode(UserResponse.self, from: d)
DispatchQueue.main.async {
self.user = decodedRes
self.hasFinished = true
print("Dispatching")
}
} else {
print("No Data")
}
} catch {
print("Error")
}
}.resume()
}
}
I have taken this section in its entirety except for minor tweaks to fit the different object from another file I have for a similar task, albeit that it has no alternate responses and so I didn't have to handle any other types of data responses.
I'm still fairly new to swift, so I have basic understanding of do-try-catch syntax, but I don't how I would catch different response models or where to place them in my code to prevent any errors from happening.
Ideally, I would like it to toggle the incorrectLogin variable, which can be observed and trigger a popup saying incorrect login information, as all login screens do when you input incorrect credentials. If it doesn't, it should just toggle the hasFinished variable and leave incorrectLogin as false, and then I would use the user model to do all of the behind the scenes stuff.
Again, I'm still fairly new to swift, I'm sure there's probably security issues here or something else I'm overlooking, and please, let me know if that's the case.
A suitable solution is an enum with associated values.
Add a struct for the error case
public struct ErrorResponse: Decodable {
let message : String
}
and the enum
enum Response : Decodable {
case success(UserResponse)
case failure(ErrorResponse)
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
do {
let userData = try container.decode(UserResponse.self)
self = .success(userData)
} catch DecodingError.typeMismatch {
let errorData = try container.decode(ErrorResponse.self)
self = .failure(errorData)
}
}
}
After decoding the data switch on the result and handle the cases
do {
if let d = data {
let result = try JSONDecoder().decode(Response.self, from: d)
switch result {
case .success(let userData):
DispatchQueue.main.async {
self.user = userData
self.hasFinished = true
print("Dispatching")
}
case .success(let errorData):
print(errorData.message)
// handle the error
}
} else {
print("No Data")
}
} catch {
print(error) // never print a meaningless literal string in a Decoding catch block
}

Unexpected non-void return value in void function - JSON Data from dataTask(with: URL) - (Swift 3.0)

I'm building an iOS app in Swift 3 that's supposed to communicate with a JSON Rest Api that I'm also building myself. The app will get all sorts of content from the Api, but for now all I need it to do is check the availability of the Api through a handshake function.
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error)
} else {
if let urlContent = data {
do {
let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
if jsonResult["response"] as! String == "Welcome, come in!" {
print("************ RESPONSE IS: ************")
print(jsonResult)
return
} else {
return
}
} catch {
print("************ JSON SERIALIZATION ERROR ************")
}
}
}
}
task.resume()
This is the dataTask I've set up and it runs just fine (When I print the jsonResult, I get the "Welcome!" message as expected. The problem is that I want my handshake function to return true or false (So that I can give an alert if the case is false.) When I try to set up a return true or false within the if-statement, I get the error: Unexpected non-void return value in void function.
My question is: How do I return the data out of the dataTask so that I can perform checks with it within my handshake function? I'm very new to Swift so all help is appreciated :)
Below is the entire class:
import Foundation
class RestApiManager: NSObject {
var apiAvailability:Bool?
func handshake() -> Bool {
let url = URL(string: "https://api.restaurapp.nl/handshake.php")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error)
} else {
if let urlContent = data {
do {
let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
if jsonResult["response"] as! String == "Welcome, come in!" {
print("************ RESPONSE IS: ************")
print(jsonResult)
return true
} else {
return false
}
} catch {
print("************ JSON SERIALIZATION ERROR ************")
}
}
}
}
task.resume()
}
}
Because you're using an asynchronous API, you can't return the bool from your handshake function. If you want to show an alert in the false case, you would replace the return false with something like:
DispatchQueue.main.async {
self.showAlert()
}
Technically you could make the handshake function pause until the network stuff was done, and return the bool, but that defeats the purpose of being asynchronous, and it would freeze your app's UI during the network activity, so I doubt that's what you want to do.

Swift JSON result compare to string [duplicate]

I am trying to get learn how to use AlamoFire and I am having trouble.
My method so far is as follows:
func siteInfo()->String?{
var info:NSDictionary!
var str:String!
Alamofire.request(.GET, MY_API_END_POINT).responseJSON {(request, response, JSON, error) in
info = JSON as NSDictionary
str = info["access_key"] as String
//return str
}
return str
}
This returns nil which is a problem. From what I have read here, this is because the request can take a while so the closure doesn't execute till after the return. The suggested solution of moving the return into the closure does not work for me and the compiler just yells (adding ->String after (request,response,JSON,error) which gives "'String' is not a subtype of void"). Same goes for the other solution provided.
Any ideas? Even some source code that is not related to this problem, that uses AlamoFire, would be helpful.
Thanks!
One way to handle this is to pass a closure (I usually call it a completionHandler) to your siteInfo function and call that inside Alamofire.request's closure:
func siteInfo(completionHandler: (String?, NSError?) -> ()) -> () {
Alamofire.request(.GET, MY_API_END_POINT).responseJSON {
(request, response, JSON, error) in
let info = JSON as? NSDictionary // info will be nil if it's not an NSDictionary
let str = info?["access_key"] as? String // str will be nil if info is nil or the value for "access_key" is not a String
completionHandler(str, error)
}
}
Then call it like this (don't forget error handling):
siteInfo { (str, error) in
if str != nil {
// Use str value
} else {
// Handle error / nil value
}
}
In the comments you asked:
So how would you save the info you collect from the get request if you
can only do stuff inside the closure and not effect objects outside of
the closure? Also, how to keep track to know when the request has
finished?
You can save the result of the get request to an instance variable in your class from inside the closure; there's nothing about the closure stopping you from doing that. What you do from there really depends on, well, what you want to do with that data.
How about an example?
Since it looks like you're getting an access key form that get request, maybe you need that for future requests made in other functions.
In that case, you can do something like this:
Note: Asynchronous programming is a huge topic; way too much to cover here. This is just one example of how you might handle the data you get back from your asynchronous request.
public class Site {
private var _accessKey: String?
private func getAccessKey(completionHandler: (String?, NSError?) -> ()) -> () {
// If we already have an access key, call the completion handler with it immediately
if let accessKey = self._accessKey {
completionHandler(accessKey, nil)
} else { // Otherwise request one
Alamofire.request(.GET, MY_API_END_POINT).responseJSON {
(request, response, JSON, error) in
let info = JSON as? NSDictionary // info will be nil if it's not an NSDictionary
let accessKey = info?["access_key"] as? String // accessKey will be nil if info is nil or the value for "access_key" is not a String
self._accessKey = accessKey
completionHandler(accessKey, error)
}
}
}
public func somethingNeedingAccessKey() {
getAccessKey { (accessKey, error) in
if accessKey != nil {
// Use accessKey however you'd like here
println(accessKey)
} else {
// Handle error / nil accessKey here
}
}
}
}
With that setup, calling somethingNeedingAccessKey() the first time will trigger a request to get the access key. Any calls to somethingNeedingAccessKey() after that will use the value already stored in self._accessKey. If you do the rest of somethingNeedingAccessKey's work inside the closure being passed to getAccessKey, you can be sure that your accessKey will always be valid. If you need another function that needs accessKey, just write it the same way somethingNeedingAccessKey is written.
public func somethingElse() {
getAccessKey { (accessKey, error) in
if accessKey != nil {
// Do something else with accessKey
} else {
// Handle nil accessKey / error here
}
}
}

AFNetworking and Swift - Save json response

I want to make a GET request in swift to get some Json data.
I tried to use AFNetworking and it works, but I don't know how to return the Json I get.
I tried with a return but it's made before the GET so I get nothing...
func makeGet(place:String) -> String
{
var str:String = ""
let manager = AFHTTPRequestOperationManager()
manager.requestSerializer.setValue("608c6c08443c6d933576b90966b727358d0066b4", forHTTPHeaderField: "X-Auth-Token")
manager.GET("http://something.com/api/\(place)",
parameters: nil,
success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in
str = "JSON: \(responseObject.description)"
println(str) //print the good thing
},
failure: { (operation: AFHTTPRequestOperation!,error: NSError!) in
str = "Error: \(error.localizedDescription)"
})
return str //return ""
}
Can you help me ?
Since you want to return the value after the webservice request is completed you have to pass the data via a delegate or a block(In swift it is called closures)
I see blocks useful here
//Above your class file create a handler alias
typealias SomeHandler = (String! , Bool!) -> Void
func makeGet(place:String , completionHandler: SomeHandler!)
{
var str:String = ""
let manager = AFHTTPRequestOperationManager()
manager.requestSerializer.setValue("608c6c08443c6d933576b90966b727358d0066b4", forHTTPHeaderField: "X-Auth-Token")
manager.GET("http://something.com/api/\(place)",
parameters: nil,
success: { (operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in
str = "JSON: \(responseObject.description)"
println(str) //print the good thing
completionHandler(str,false) //str as response json, false as error value
},
failure: { (operation: AFHTTPRequestOperation!,error: NSError!) in
str = "Error: \(error.localizedDescription)"
completionHandler("Error",true)
})
//return str //return "" You don't want to return anything here
}
When you want to call the method get the values like this
makeGet(){
yourJSONString , errorValue in //Here the value will be passed after you get the response
if !errorValue {
println("The End."
}
}
More about swift closures
FYI: AFNetworking owner has created a new Networking layer for swift and it is called Alamofire (AF from AFNetworking is Alamofire :])
You're not getting a response from that function, because the GET operation happens asynchronously. That is, the order of execution looks like this:
You call makeGet
makeGet creates manager, which fires off a GET request
makeGet finishes executing and returns an empty string
(some time later) manager receives a value back from the server and executes either the success or failure block.
So the only time you have access to the JSON that comes back from the server is in step 4, and you need to find a way of storing that value so you can parse it or use it or whatever. There are a variety of options here -- one is to define closures that call event handlers on your class instance, like this:
class MyClass {
func jsonLoaded(json: String) {
println("JSON: \(json)")
}
func jsonFailed(error: NSError) {
println("Error: \(error.localizedDescription)")
}
func makeGet(place:String) {
let manager = AFHTTPRequestOperationManager()
manager.requestSerializer.setValue("608c6c08443c6d933576b90966b727358d0066b4", forHTTPHeaderField: "X-Auth-Token")
manager.GET("http://something.com/api/\(place)",
parameters: nil,
success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in
self.jsonLoaded(responseObject.description)
},
failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in
self.jsonFailed(error)
}
)
}
}
let manager = AFHTTPSessionManager()
manager.GET("http://api.androidhive.info/json/movies.json", parameters: nil, success: { (operation, responseObject) -> Void in
print(responseObject)
}, failure: nil)
AFHTTPRequestOperationManager is not available in latest AFnetworking library, it has replaced with AFHTTPSessionManager.
This is a simple example of getting response object.

#try equivalent in Swift? [duplicate]

I haven't read too much into Swift but one thing I noticed is that there are no exceptions.
So how do they do error handling in Swift? Has anyone found anything related to error-handling?
Swift 2 & 3
Things have changed a bit in Swift 2, as there is a new error-handling mechanism, that is somewhat more similar to exceptions but different in detail.
1. Indicating error possibility
If function/method wants to indicate that it may throw an error, it should contain throws keyword like this
func summonDefaultDragon() throws -> Dragon
Note: there is no specification for type of error the function actually can throw. This declaration simply states that the function can throw an instance of any type implementing ErrorType or is not throwing at all.
2. Invoking function that may throw errors
In order to invoke function you need to use try keyword, like this
try summonDefaultDragon()
this line should normally be present do-catch block like this
do {
let dragon = try summonDefaultDragon()
} catch DragonError.dragonIsMissing {
// Some specific-case error-handling
} catch DragonError.notEnoughMana(let manaRequired) {
// Other specific-case error-handlng
} catch {
// Catch all error-handling
}
Note: catch clause use all the powerful features of Swift pattern matching so you are very flexible here.
You may decided to propagate the error, if your are calling a throwing function from a function that is itself marked with throws keyword:
func fulfill(quest: Quest) throws {
let dragon = try summonDefaultDragon()
quest.ride(dragon)
}
Alternatively, you can call throwing function using try?:
let dragonOrNil = try? summonDefaultDragon()
This way you either get the return value or nil, if any error occurred. Using this way you do not get the error object.
Which means that you can also combine try? with useful statements like:
if let dragon = try? summonDefaultDragon()
or
guard let dragon = try? summonDefaultDragon() else { ... }
Finally, you can decide that you know that error will not actually occur (e.g. because you have already checked are prerequisites) and use try! keyword:
let dragon = try! summonDefaultDragon()
If the function actually throws an error, then you'll get a runtime error in your application and the application will terminate.
3. Throwing an error
In order to throw an error you use throw keyword like this
throw DragonError.dragonIsMissing
You can throw anything that conforms to ErrorType protocol. For starters NSError conforms to this protocol but you probably would like to go with enum-based ErrorType which enables you to group multiple related errors, potentially with additional pieces of data, like this
enum DragonError: ErrorType {
case dragonIsMissing
case notEnoughMana(requiredMana: Int)
...
}
Main differences between new Swift 2 & 3 error mechanism and Java/C#/C++ style exceptions are follows:
Syntax is a bit different: do-catch + try + defer vs traditional try-catch-finally syntax.
Exception handling usually incurs much higher execution time in exception path than in success path. This is not the case with Swift 2.0 errors, where success path and error path cost roughly the same.
All error throwing code must be declared, while exceptions might have been thrown from anywhere. All errors are "checked exceptions" in Java nomenclature. However, in contrast to Java, you do not specify potentially thrown errors.
Swift exceptions are not compatible with ObjC exceptions. Your do-catch block will not catch any NSException, and vice versa, for that you must use ObjC.
Swift exceptions are compatible with Cocoa NSError method conventions of returning either false (for Bool returning functions) or nil (for AnyObject returning functions) and passing NSErrorPointer with error details.
As an extra syntatic-sugar to ease error handling, there are two more concepts
deferred actions (using defer keyword) which let you achieve the same effect as finally blocks in Java/C#/etc
guard statement (using guard keyword) which let you write little less if/else code than in normal error checking/signaling code.
Swift 1
Runtime errors:
As Leandros suggests for handling runtime errors (like network connectivity problems, parsing data, opening file, etc) you should use NSError like you did in ObjC, because the Foundation, AppKit, UIKit, etc report their errors in this way. So it's more framework thing than language thing.
Another frequent pattern that is being used are separator success/failure blocks like in AFNetworking:
var sessionManager = AFHTTPSessionManager(baseURL: NSURL(string: "yavin4.yavin.planets"))
sessionManager.HEAD("/api/destoryDeathStar", parameters: xwingSquad,
success: { (NSURLSessionDataTask) -> Void in
println("Success")
},
failure:{ (NSURLSessionDataTask, NSError) -> Void in
println("Failure")
})
Still the failure block frequently received NSError instance, describing the error.
Programmer errors:
For programmer errors (like out of bounds access of array element, invalid arguments passed to a function call, etc) you used exceptions in ObjC. Swift language does not seem to have any language support for exceptions (like throw, catch, etc keyword). However, as documentation suggests it is running on the same runtime as ObjC, and therefore you are still able to throw NSExceptions like this:
NSException(name: "SomeName", reason: "SomeReason", userInfo: nil).raise()
You just cannot catch them in pure Swift, although you may opt for catching exceptions in ObjC code.
The questions is whether you should throw exceptions for programmer errors, or rather use assertions as Apple suggests in the language guide.
Update June 9th 2015 - Very important
Swift 2.0 comes with try, throw, and catch keywords and the most exciting is:
Swift automatically translates Objective-C methods that produce errors into methods that throw an error according to Swift's native error handling functionality.
Note: Methods that consume errors, such as delegate methods or methods
that take a completion handler with an NSError object argument, do not
become methods that throw when imported by Swift.
Excerpt From: Apple Inc. “Using Swift with Cocoa and Objective-C (Swift 2 Prerelease).” iBooks.
Example: (from the book)
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *URL = [NSURL fileURLWithPath:#"/path/to/file"];
NSError *error = nil;
BOOL success = [fileManager removeItemAtURL:URL error:&error];
if (!success && error){
NSLog(#"Error: %#", error.domain);
}
The equivalent in swift will be:
let fileManager = NSFileManager.defaultManager()
let URL = NSURL.fileURLWithPath("path/to/file")
do {
try fileManager.removeItemAtURL(URL)
} catch let error as NSError {
print ("Error: \(error.domain)")
}
Throwing an Error:
*errorPtr = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCannotOpenFile userInfo: nil]
Will be automatically propagated to the caller:
throw NSError(domain: NSURLErrorDomain, code: NSURLErrorCannotOpenFile, userInfo: nil)
From Apple books, The Swift Programming Language it's seems errors should be handle using enum.
Here is an example from the book.
enum ServerResponse {
case Result(String, String)
case Error(String)
}
let success = ServerResponse.Result("6:00 am", "8:09 pm")
let failure = ServerResponse.Error("Out of cheese.")
switch success {
case let .Result(sunrise, sunset):
let serverResponse = "Sunrise is at \(sunrise) and sunset is at \(sunset)."
case let .Error(error):
let serverResponse = "Failure... \(error)"
}
From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/br/jEUH0.l
Update
From Apple news books, "Using Swift with Cocoa and Objective-C". Runtime exceptions not occur using swift languages, so that's why you don't have try-catch. Instead you use Optional Chaining.
Here is a stretch from the book:
For example, in the code listing below, the first and second lines are
not executed because the length property and the characterAtIndex:
method do not exist on an NSDate object. The myLength constant is
inferred to be an optional Int, and is set to nil. You can also use an
if–let statement to conditionally unwrap the result of a method that
the object may not respond to, as shown on line three
let myLength = myObject.length?
let myChar = myObject.characterAtIndex?(5)
if let fifthCharacter = myObject.characterAtIndex(5) {
println("Found \(fifthCharacter) at index 5")
}
Excerpt From: Apple Inc. “Using Swift with Cocoa and Objective-C.” iBooks. https://itun.es/br/1u3-0.l
And the books also encourage you to use cocoa error pattern from Objective-C (NSError Object)
Error reporting in Swift follows the same pattern it does in
Objective-C, with the added benefit of offering optional return
values. In the simplest case, you return a Bool value from the
function to indicate whether or not it succeeded. When you need to
report the reason for the error, you can add to the function an
NSError out parameter of type NSErrorPointer. This type is roughly
equivalent to Objective-C’s NSError **, with additional memory safety
and optional typing. You can use the prefix & operator to pass in a
reference to an optional NSError type as an NSErrorPointer object, as
shown in the code listing below.
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/br/1u3-0.l
There are no Exceptions in Swift, similar to Objective-C's approach.
In development, you can use assert to catch any errors which might appear, and need to be fixed before going to production.
The classic NSError approach isn't altered, you send an NSErrorPointer, which gets populated.
Brief example:
var error: NSError?
var contents = NSFileManager.defaultManager().contentsOfDirectoryAtPath("/Users/leandros", error: &error)
if let error = error {
println("An error occurred \(error)")
} else {
println("Contents: \(contents)")
}
The recommended 'Swift Way' is:
func write(path: String)(#error: NSErrorPointer) -> Bool { // Useful to curry error parameter for retrying (see below)!
return "Hello!".writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding, error: error)
}
var writeError: NSError?
let written = write("~/Error1")(error: &writeError)
if !written {
println("write failure 1: \(writeError!.localizedDescription)")
// assert(false) // Terminate program
}
However I prefer try/catch as I find it easier to follow because it moves the error handling to a separate block at the end, this arrangement is sometimes called "Golden Path". Lucky you can do this with closures:
TryBool {
write("~/Error2")(error: $0) // The code to try
}.catch {
println("write failure 2: \($0!.localizedDescription)") // Report failure
// assert(false) // Terminate program
}
Also it is easy to add a retry facility:
TryBool {
write("~/Error3")(error: $0) // The code to try
}.retry {
println("write failure 3 on try \($1 + 1): \($0!.localizedDescription)")
return write("~/Error3r") // The code to retry
}.catch {
println("write failure 3 catch: \($0!.localizedDescription)") // Report failure
// assert(false) // Terminate program
}
The listing for TryBool is:
class TryBool {
typealias Tryee = NSErrorPointer -> Bool
typealias Catchee = NSError? -> ()
typealias Retryee = (NSError?, UInt) -> Tryee
private var tryee: Tryee
private var retries: UInt = 0
private var retryee: Retryee?
init(tryee: Tryee) {
self.tryee = tryee
}
func retry(retries: UInt, retryee: Retryee) -> Self {
self.retries = retries
self.retryee = retryee
return self
}
func retry(retryee: Retryee) -> Self {
return self.retry(1, retryee)
}
func retry(retries: UInt) -> Self {
// For some reason you can't write the body as "return retry(1, nil)", the compiler doesn't like the nil
self.retries = retries
retryee = nil
return self
}
func retry() -> Self {
return retry(1)
}
func catch(catchee: Catchee) {
var error: NSError?
for numRetries in 0...retries { // First try is retry 0
error = nil
let result = tryee(&error)
if result {
return
} else if numRetries != retries {
if let r = retryee {
tryee = r(error, numRetries)
}
}
}
catchee(error)
}
}
You can write a similar class for testing an Optional returned value instead of Bool value:
class TryOptional<T> {
typealias Tryee = NSErrorPointer -> T?
typealias Catchee = NSError? -> T
typealias Retryee = (NSError?, UInt) -> Tryee
private var tryee: Tryee
private var retries: UInt = 0
private var retryee: Retryee?
init(tryee: Tryee) {
self.tryee = tryee
}
func retry(retries: UInt, retryee: Retryee) -> Self {
self.retries = retries
self.retryee = retryee
return self
}
func retry(retryee: Retryee) -> Self {
return retry(1, retryee)
}
func retry(retries: UInt) -> Self {
// For some reason you can't write the body as "return retry(1, nil)", the compiler doesn't like the nil
self.retries = retries
retryee = nil
return self
}
func retry() -> Self {
return retry(1)
}
func catch(catchee: Catchee) -> T {
var error: NSError?
for numRetries in 0...retries {
error = nil
let result = tryee(&error)
if let r = result {
return r
} else if numRetries != retries {
if let r = retryee {
tryee = r(error, numRetries)
}
}
}
return catchee(error)
}
}
The TryOptional version enforces a non-Optional return type that makes subsequent programming easier, e.g. 'Swift Way:
struct FailableInitializer {
init?(_ id: Int, error: NSErrorPointer) {
// Always fails in example
if error != nil {
error.memory = NSError(domain: "", code: id, userInfo: [:])
}
return nil
}
private init() {
// Empty in example
}
static let fallback = FailableInitializer()
}
func failableInitializer(id: Int)(#error: NSErrorPointer) -> FailableInitializer? { // Curry for retry
return FailableInitializer(id, error: error)
}
var failError: NSError?
var failure1Temp = failableInitializer(1)(error: &failError)
if failure1Temp == nil {
println("failableInitializer failure code: \(failError!.code)")
failure1Temp = FailableInitializer.fallback
}
let failure1 = failure1Temp! // Unwrap
Using TryOptional:
let failure2 = TryOptional {
failableInitializer(2)(error: $0)
}.catch {
println("failableInitializer failure code: \($0!.code)")
return FailableInitializer.fallback
}
let failure3 = TryOptional {
failableInitializer(3)(error: $0)
}.retry {
println("failableInitializer failure, on try \($1 + 1), code: \($0!.code)")
return failableInitializer(31)
}.catch {
println("failableInitializer failure code: \($0!.code)")
return FailableInitializer.fallback
}
Note auto-unwrapping.
Edit: Although this answer works, it is little more than Objective-C transliterated into Swift. It has been made obsolete by changes in Swift 2.0. Guilherme Torres Castro's answer above is a very good introduction to the preferred way of handling errors in Swift. VOS
It took a bit of figuring it out but I think I've sussed it. It seems ugly though. Nothing more than a thin skin over the Objective-C version.
Calling a function with an NSError parameter...
var fooError : NSError ? = nil
let someObject = foo(aParam, error:&fooError)
// Check something was returned and look for an error if it wasn't.
if !someObject {
if let error = fooError {
// Handle error
NSLog("This happened: \(error.localizedDescription)")
}
} else {
// Handle success
}`
Writing the function that takes an error parameter...
func foo(param:ParamObject, error: NSErrorPointer) -> SomeObject {
// Do stuff...
if somethingBadHasHappened {
if error {
error.memory = NSError(domain: domain, code: code, userInfo: [:])
}
return nil
}
// Do more stuff...
}
Basic wrapper around objective C that gives you the try catch feature.
https://github.com/williamFalcon/SwiftTryCatch
Use like:
SwiftTryCatch.try({ () -> Void in
//try something
}, catch: { (error) -> Void in
//handle error
}, finally: { () -> Void in
//close resources
})
As Guilherme Torres Castro said, in Swift 2.0, try, catch, do can be used in the programming.
For example, In CoreData fetch data method, instead of put &error as a parameter into the managedContext.executeFetchRequest(fetchRequest, error: &error), now we only need to use use managedContext.executeFetchRequest(fetchRequest) and then handle the error with try, catch (Apple Document Link)
do {
let fetchedResults = try managedContext.executeFetchRequest(fetchRequest) as? [NSManagedObject]
if let results = fetchedResults{
people = results
}
} catch {
print("Could not fetch")
}
If you have already download the xcode7 Beta. Try to search throwing errors in Documentations and API Reference and choose the first showing result, it gives a basic idea what can be done for this new syntax. However, fully documentation is not post for many APIs yet.
More fancy Error Handling techniques can be found in
What's New in Swift (2015 Session 106 28m30s)
This is an update answer for swift 2.0. I am looking forward feature rich Error handling model like in java. Finally, they announced the good news. here
Error handling model: The new error handling model in Swift 2.0 will
instantly feel natural, with familiar try, throw, and catch keywords.
Best of all, it was designed to work perfectly with the Apple SDKs and
NSError. In fact, NSError conforms to a Swift’s ErrorType. You’ll
definitely want to watch the WWDC session on What’s New in Swift to
hear more about it.
e.g :
func loadData() throws { }
func test() {
do {
try loadData()
} catch {
print(error)
}}
Starting with Swift 2, as others have already mentioned, error handling is best accomplished through the use of do/try/catch and ErrorType enums. This works quite well for synchronous methods, but a little cleverness is required for asynchronous error handling.
This article has a great approach to this problem:
https://jeremywsherman.com/blog/2015/06/17/using-swift-throws-with-completion-callbacks/
To summarize:
// create a typealias used in completion blocks, for cleaner code
typealias LoadDataResult = () throws -> NSData
// notice the reference to the typealias in the completionHandler
func loadData(someID: String, completionHandler: LoadDataResult -> Void)
{
completionHandler()
}
then, the call to the above method would be as follows:
self.loadData("someString",
completionHandler:
{ result: LoadDataResult in
do
{
let data = try result()
// success - go ahead and work with the data
}
catch
{
// failure - look at the error code and handle accordingly
}
})
This seems a bit cleaner than having a separate errorHandler callback passed to the asynchronous function, which was how this would be handled prior to Swift 2.
Error handling is a new feature of Swift 2.0. It uses the try, throw and catch keywords.
See the Apple Swift 2.0 announcement on the official Apple Swift blog
Nice and simple lib to handle exception:
TryCatchFinally-Swift
Like a few others it wraps around the objective C exception features.
Use it like this:
try {
println(" try")
}.catch { e in
println(" catch")
}.finally {
println(" finally")
}
enum CheckValidAge : Error{
case overrage
case underage
}
func checkValidAgeForGovernmentJob(age:Int)throws -> Bool{
if age < 18{
throw CheckValidAge.underage
}else if age > 25{
throw CheckValidAge.overrage
}else{
return true
}
}
do {
try checkValidAgeForGovernmentJob(age: 26)
print("You are valid for government job ")
}catch CheckValidAge.underage{
print("You are underage for government job ")
}catch CheckValidAge.overrage{
print("You are overrage for government job ")
}
Change age in try checkValidAgeForGovernmentJob(age: 26)
Out Put
You are overrage for government job
What I have seen is that because of the nature of the device you don't want to be throwing a bunch of cryptic error handling messages at the user. That is why most functions return optional values then you just code to ignore the optional. If a function comes back nil meaning it failed you can pop a message or whatever.