swift - a function does internet fetching and return a value -
i know following piece of code wrong, want show intent. want write method called multiple times. , fetching method tell me if reached.
func fetch(url: string) -> bool? { let defaultsession = urlsession(configuration: urlsessionconfiguration.default) let url = url(string: url) var bool: bool? = nil if let url = url { defaultsession.datatask(with: url, completionhandler: { data, response, error in if let error = error { print(error) return } dispatchqueue.main.async { if let httpresponse = response as? httpurlresponse, 200...299 ~= httpresponse.statuscode, let data = data { // handle data. bool = true } else { print("something wrong") bool = false } } }).resume() } return bool } if let bool = fetch(url: "https://www.google.com.hk/webhp?hl=en&sa=x&ved=0ahukewimubk7r-hvahvfmzqkhazmammqpagd"), bool == true { // if true, can go next step. }
making ui wait on completion of api call not recommended. app have no control on how long api call take. situations bad network connectivity can take several seconds respond.
you can handle situation use completion handler.
func fetch(url: string, completion: @escaping (_ success: bool) -> void) { let defaultsession = urlsession(configuration: urlsessionconfiguration.default) let url = url(string: url) if let url = url { defaultsession.datatask(with: url, completionhandler: { data, response, error in if let error = error { print(error) return } if let httpresponse = response as? httpurlresponse, 200...299 ~= httpresponse.statuscode, let data = data { // handle data. completion(true) } else { print("something wrong") completion(false) } }).resume() } } func testfetch () { fetch(url: "https://www.google.com.hk/webhp?hl=en&sa=x&ved=0ahukewimubk7r-hvahvfmzqkhazmammqpagd") { (success) in // if true, can go next step. dispatchqueue.main.async { if success { // } else { // not } } } }
Comments
Post a Comment