Created
March 29, 2019 08:56
-
-
Save nhathm/ec40fc2bdb5c215d731f134e115f36d0 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
enum ServerError: Error { | |
case urlFailed | |
case networkFailed | |
case serverFailed | |
case dataFailed | |
} | |
func fetchDataFromServer(_ urlString: String, completion: @escaping (Result<Data, ServerError>) -> ()) { | |
// Check if URL valid | |
guard let url = URL(string: urlString) else { | |
completion(.failure(.urlFailed)) | |
return | |
} | |
let defaultSession = URLSession(configuration: URLSessionConfiguration.default) | |
let dataTask : URLSessionTask = defaultSession.dataTask(with: url) { data, response, error in | |
guard error == nil else { | |
completion(.failure(.serverFailed)) | |
return | |
} | |
guard let data = data else { | |
completion(.failure(.dataFailed)) | |
return | |
} | |
completion(.success(data)) | |
} | |
dataTask.resume() | |
} | |
fetchDataFromServer("https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22") { result in | |
switch result { | |
case .success(let data): | |
print("Data from server = \(String(data: data, encoding: .utf8) ?? "Convert data to string failed")") | |
case .failure(let error): | |
print("Error: \(error)") | |
} | |
// Use get() method of Result type to get value sample | |
// if let data = try? result.get() { | |
// print("Data from server = \(String(data: data, encoding: .utf8) ?? "Convert data to string failed")") | |
// } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment