Skip to content

Instantly share code, notes, and snippets.

@ChenCodes
Created December 27, 2016 21:43
Show Gist options
  • Save ChenCodes/e45bd03a216c214ba310b1164d74ae79 to your computer and use it in GitHub Desktop.
Save ChenCodes/e45bd03a216c214ba310b1164d74ae79 to your computer and use it in GitHub Desktop.
background_thread.swift
// Without threading
func slow() {
let methodStart = Date()
let url = URL(string: "some string url goes here for an image")
do {
let data = try Data(contentsOf: url!)
self.imageView.image = UIImage(data: data)
} catch {
print("error"
}
let methodFinish = Date()
let executionTime = methodFinish.timeIntervalSince(methodStart)
print("Execution Time: \(executionTime)")
}
// With threading
func fast() {
DispatchQueue.global(qos: .background).async {
let methodStart = Date()
let url = URL(string: "same string as one above")
do {
let data = try Data(contentsOf: url!)
// go back to main thread to update user interface
DispatchQueue.main.async {
self.imageView.image = UIImage(data: data)
let methodFinish = Date()
let executionTime = methodFinish.timeIntervalSince(methodStart)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment