Created
December 27, 2016 21:43
-
-
Save ChenCodes/e45bd03a216c214ba310b1164d74ae79 to your computer and use it in GitHub Desktop.
background_thread.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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