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

Popular posts from this blog

What is happening when Matlab is starting a "parallel pool"? -

angular - DownloadURL return null in below code -

php - Cannot override Laravel Spark authentication with own implementation -