Skip to content

Instantly share code, notes, and snippets.

@kwmt
Created June 13, 2019 06:44
Show Gist options
  • Save kwmt/03e7e60f9ed9d27d5ea994a22a94417d to your computer and use it in GitHub Desktop.
Save kwmt/03e7e60f9ed9d27d5ea994a22a94417d to your computer and use it in GitHub Desktop.
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