GithubHelp home page GithubHelp logo

kisso / repetitivetask Goto Github PK

View Code? Open in Web Editor NEW

This project forked from krzyzanowskim/repetitivetask

0.0 0.0 0.0 10 KB

Home Page: http://blog.krzyzanowskim.com/2016/01/06/retry-in-the-wild/

License: MIT License

Swift 100.00%

repetitivetask's Introduction

RepetitiveTask

Implementation of Retry pattern in Swift for iOS/OSX.

Definition of repetitive task

HTTP request with retry:

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 = httpBody

        let 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

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)")
         })

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.