Created
June 13, 2019 06:44
-
-
Save kwmt/03e7e60f9ed9d27d5ea994a22a94417d to your computer and use it in GitHub Desktop.
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
import Foundation | |
import PlaygroundSupport | |
PlaygroundPage.current.needsIndefiniteExecution = true | |
let url = URL(string: "https://jsonplaceholder.typicode.com/posts/1")! | |
func fetch(callback:( (String) -> Void)? = nil) { | |
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in | |
guard error == nil else { | |
callback?(error?.localizedDescription ?? "エラーです") | |
return | |
} | |
guard let data = data, let contents = String(data: data, encoding: String.Encoding.utf8) else { | |
callback?("変換エラーです") | |
return | |
} | |
callback?(contents) | |
} | |
task.resume() | |
} | |
fetch { content in | |
print(content) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment