it seems me changes ios8.4 maybe. completion block nsurlsession datataskwithrequest running on main thread rather thread executing resume. new and/or correct behavior?
there many postings this users want completion code on main thread, find there (breaking code). here isolated sample:
func application(application: uiapplication, didfinishlaunchingwithoptions launchoptions: [nsobject: anyobject]?) -> bool { // override point customization after application launch. dispatch_async(dispatch_get_global_queue(qos_class_background, 0)) { self.threadtest() } return true } func threadtest() { println("threadtest on main thread: \(nsthread.currentthread().ismainthread)") let urlstring = "http://www.apple.com/contact/" let url = nsurl(string:urlstring) var request = nsmutableurlrequest(url: url!) var configuration = nsurlsessionconfiguration.defaultsessionconfiguration() var session = nsurlsession(configuration: configuration, delegate:nil, delegatequeue:nsoperationqueue.mainqueue()) var task = session.datataskwithrequest(request) { (data: nsdata!, response: nsurlresponse!, error: nserror!) -> void in if error != nil { print("error: \(error.localizeddescription)") } else { if let result = nsstring(data: data, encoding:nsasciistringencoding) { let partial = result.substringtoindex(10) println("retrieved page: \(partial)...") println("nsurlsession.datatashwithrequest completion block on main thread: \(nsthread.currentthread().ismainthread)") } } } task.resume() } with results:
threadtest on main thread: false retrieved page:
<!doctype ...nsurlsession.datatashwithrequest completion block on main thread: true
i figured out answer. thread of completion handler setup in init of nsurlsession.
from documentation:
init(configuration configuration: nsurlsessionconfiguration, delegate delegate: nsurlsessiondelegate?, delegatequeue queue: nsoperationqueue?)
queue - queue scheduling delegate calls , completion handlers. if nil, session creates serial operation queue performing delegate method calls , completion handler calls.
my code setup completion on main thread:
var session = nsurlsession(configuration: configuration, delegate:nil, delegatequeue:nsoperationqueue.mainqueue())
Comments
Post a Comment