Skip to content

Instantly share code, notes, and snippets.

fetchPromise().then { value in
// do something
}.catch { error in {
// in case of error
}
Promise() { fulfill, reject in
return "Hello World" //or other async code
}
Promise() { fulfill, reject in
// code
}
class NetworkOperation: Operation {
var targetURL: String?
var resultData: Data?
var _finished = false
override var isFinished: Bool {
get {
return _finished
}
set (newValue) {
willChangeValue(for: \.isFinished)
public class ApiRequestDelegate:NSObject, URLSessionDelegate, URLSessionTaskDelegate,
URLSessionDataDelegate{
// called once as soon as a response returns
public func urlSession(session: URLSession, dataTask: URLSessionDataTask,
didReceiveResponse response: URLResponse,
completionHandler: (URLSession.ResponseDisposition) -> Void) {
// store Response to further process it and call completion Handler to continue
}
URLSession.shared.dataTask(with: backendurl!) { data, _, error in
if error != nil {
print(error)
return
}
let imageurl = String(data: data!, encoding: String.Encoding.utf8) as String! // For simplicity response is only the URL
URLSession.shared.dataTask(with: URL(string:imageurl!)!) { (data, response, error) in
if error != nil {
print(error)
URLSession.shared.dataTask(with: url!) { data, _, error in
if error != nil {
print(error)
return
}
DispatchQueue.main.async {
imageView.image = UIImage(data: data!)
}
}.resume()
let op1 = Operation()
op1.name = "Operation1"
OperationQueue.main.addOperations([op1], waitUntilFinished:false)
let operations = OperationQueue.main.operations
operations.map { op in
if op.name == "Operation1" {
op.cancel()
}
import Foundation
class UIOperation: AsyncOperation {
let viewController: UIViewcontroller!
override func execute() {
let alert = UIAlertController(title: "My Alert", message: @"This is an alert.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .`default`, handler: { _ in
self.handleInput()
}))
class GroupOperation: AsyncOperation {
let queue = OperationQueue()
var operations: [AsyncOperation] = []
var errors: [Error] = []
override func execute() {
print("group started")
queue.addOperations(operations, waitUntilFinished: true)
print("group done")
}