https://github.com/krzyzanowskim/repetitivetask
https://github.com/krzyzanowskim/repetitivetask
Last synced: 7 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/krzyzanowskim/repetitivetask
- Owner: krzyzanowskim
- License: mit
- Created: 2016-01-06T23:43:09.000Z (almost 10 years ago)
- Default Branch: master
- Last Pushed: 2017-09-01T13:46:33.000Z (about 8 years ago)
- Last Synced: 2024-04-14T07:11:18.656Z (over 1 year ago)
- Language: Swift
- Homepage: http://blog.krzyzanowskim.com/2016/01/06/retry-in-the-wild/
- Size: 9.77 KB
- Stars: 40
- Watchers: 5
- Forks: 7
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# RepetitiveTask
Implementation of Retry pattern in Swift for iOS/OSX.### Definition of repetitive task
HTTP request with retry:
```swift
struct FailableTransientURLTask: RepetitiveTaskProtocol {
private var session: NSURLSession?
private var url: NSURL
private var archivedParameters: NSData/// Input parameters for the Task. This should be adjusted for the actual Task
/// For this example required input is in parameters
init(session: NSURLSession, url: NSURL, parameters: NSCoding) {
self.session = session
self.url = url
self.archivedParameters = NSKeyedArchiver.archivedDataWithRootObject(parameters)
}/// Run the request
func run(completion: RepetitiveTaskProtocolCompletion) {
guard let parameters = NSKeyedUnarchiver.unarchiveObjectWithData(self.archivedParameters), httpBody = try? NSJSONSerialization.dataWithJSONObject(parameters, options: []) else
{
fatalError("Missing parameters")
}let request = NSMutableURLRequest(URL: self.url)
request.HTTPBody = httpBodylet sessionURLTask = session?.dataTaskWithRequest(request) { (data, response, error) in
// success and error handling
if let data = data {
completion(RepetitiveTaskResult(success: data))
} else if let error = error {
// check if error is transient or final and throw right error
if let delay = error.userInfo["ErrorRetryDelayKey"] as? NSNumber {
// request failed and can be retry later
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(delay.doubleValue * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), {
completion(RepetitiveTaskResult(error: RepetitiveTaskError.RetryDelay(delay.doubleValue)))
})
} else {
// request failed for other reason
completion(RepetitiveTaskResult(error: RepetitiveTaskError.Failed(error)))
}
} else {
// no data received scenario
completion(RepetitiveTaskResult(error: RepetitiveTaskError.NoData))
}
}sessionURLTask?.resume()
}
}
```###usage
```swift
let task = FailableTransientURLTask(session: NSURLSession.sharedSession(), url: NSURL(string: "http://blog.krzyzanowskim.com/rss")!, parameters: ["foo": "bar"])//: Run task maximum 3 times hoping for success
task.run(retryCount: 3,
failure: { (error) -> Void in
print("failure \(error)")
},
success: { (data) -> Void in
print("success \(data)")
})
```