Created
March 29, 2019 08:45
-
-
Save nhathm/29a4b730863ec6e9aadb1d6e499f9100 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
func fetchDataFromServer(_ urlString: String, completion: @escaping (Data?, String?) -> ()) { | |
// Check if URL valid | |
guard let url = URL(string: urlString) else { | |
completion(nil, "Invalid URL") | |
return | |
} | |
let defaultSession = URLSession(configuration: URLSessionConfiguration.default) | |
let dataTask : URLSessionTask = defaultSession.dataTask(with: url) { data, response, error in | |
guard error == nil else { | |
completion(nil, error!.localizedDescription) | |
return | |
} | |
guard let data = data else { | |
completion(nil, "Get data failed") | |
return | |
} | |
completion(data, nil) | |
} | |
dataTask.resume() | |
} | |
fetchDataFromServer("https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22") { (data, error) in | |
if let error = error { | |
print("Get data failed: \(error)") | |
return | |
} | |
if let data = data { | |
print("Data from server = \(String(data: data, encoding: .utf8) ?? "Convert data failed")") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment