A simple promise framework for Swift.
This small library implements thread safe promises for Swift. It allows to create promises and fulfill or reject them asynchronously. Promises can be chained using the then
method. Furthermore it has support for cancelling a promise chain.
let promise: Promise<String> = Promise { (_, fulfill, reject) in
performSomeAsynchronousTaskWithCompletion() { (resultString: String?, error: ErrorType?) in
if let string = resultString {
fulfill(string)
}
else {
reject(error)
}
}
}
promise.success { string in
print("The result is: \(string)")
}.failure { error in
print("Something went wrong: \(error)")
}
promise.then { (string) -> AnyObject in
guard let data = string.dataUsingEncoding(NSUTF8StringEncoding) else {
throw PromiseError.Generic
}
return try NSJSONSerialization.JSONObjectWithData(data, options: [])
}.success { (jsonObject) in
print("Parsed json object: \(jsonObject)")
}.failure { error in
print("Could not parse json: \(error)")
}
Using CocoaPods:
use_frameworks!
pod 'SwiftyPromise'
Using Carthage:
github "sroebert/SwiftyPromise"
Manually:
- Drag
SwiftyPromise.xcodeproj
to your project in the Project Navigator. - Select your project and then your app target. Open the Build Phases panel.
- Expand the Target Dependencies group, and add
SwiftyPromise.framework
. - Click on the
+
button at the top left of the panel and select New Copy Files Phase. Set Destination to Frameworks, and addSwiftyPromise.framework
. import SwiftyPromise
whenever you want to use SwiftyPromise.
- iOS 8.0+, Mac OS X 10.9+, tvOS 9.0+ or watchOS 2.0+
- Swift 3.0
Steven Roebert (@sroebert)
SwiftyPromise is available under the MIT license.