Skip to content

Instantly share code, notes, and snippets.

@marcboeren
Created March 19, 2015 22:43
Show Gist options
  • Save marcboeren/c5bae523b1df8febc238 to your computer and use it in GitHub Desktop.
Save marcboeren/c5bae523b1df8febc238 to your computer and use it in GitHub Desktop.
Use Alamofire & SwiftyJSON to POST to a JSON API, retry every second unless cancelled or successful
import Alamofire
class Something {
var postCancelled: Bool = false
func postToIp(ip: String) {
let parameters = [
"a": "value 1",
"b": "value 2",
]
Alamofire.request(.POST, "http://\(ip)/api", parameters: parameters, encoding: .JSON)
.responseJSON({ (_, _, jsondata, _) in
let jsondata = JSON(jsondata!) // this is SwiftyJSON
if let success = jsondata["success"].dictionary {
println("test succeeded")
} else {
if (!self.postCancelled) {
println("retry after 1 second")
let delayInSeconds = 1.0
let delay = dispatch_time(DISPATCH_TIME_NOW, Int64(delayInSeconds * Double(NSEC_PER_SEC)))
dispatch_after(delay, dispatch_get_main_queue()) {
println("retrying...")
self.postToIp(ip)
}
}
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment