swift - Fetching data from internet in terminal -
when played code using xcode playground, following code works. can dispatched main queue , print in main queue..
but when inserted following code , build code bash command. doesn't work. printed out lines except in main queue..
therefore, believe if code complied bash command when code run dispatchqueue.main.async, happen cannot dispatched main queue. how can fix that?
import foundation let defaultsession = urlsession(configuration: urlsessionconfiguration.default) let url = url(string: "https://api.pearson.com/v2/dictionaries/ldec/entries?headword=test&apikey=zaonrfmzzsfq4h4f53kjbpozq9cujtns") if let url = url { print("start") defaultsession.datatask(with: url, completionhandler: {data, response, error in print("other queue.") if let error = error { print(error) return } else if let httpresponse = response as? httpurlresponse, 200...299 ~= httpresponse.statuscode, let data = data {//, let result = data as? dictionary<string, any> { //print(result) print("going main queue") dispatchqueue.main.async { print("in main queue.") } } else { print("something wrong") } }).resume() } while true {}
have @ code below. work playground , terminal.
import foundation var isrunning: bool = true let defaultsession = urlsession(configuration: urlsessionconfiguration.default) let url = url(string: "http://www.google.com")! print("start") defaultsession.datatask(with: url, completionhandler: {data, response, error in print("other queue.") if let error = error { print(error) return } else if let httpresponse = response as? httpurlresponse, 200...299 ~= httpresponse.statuscode, let data = data { print("before main queue - ismainthread=",thread.current.ismainthread) dispatchqueue.main.async { print("executed in main queue - ismainthread=",thread.current.ismainthread) // may consider exiting while loop isrunning = false } } else { print("something wrong") } }).resume() while(isrunning) { runloop.current.run(mode: runloopmode.defaultrunloopmode, before: date()) usleep(3) }
Comments
Post a Comment