Swift: Block mainThread until function finished loading data / NSURLSession with completionHandler -


i want create function loads data url , returns responsedata nsdata. want block mainthread until data finished. here have far:

function:

typealias completionblock = (nsdata!, nsurlresponse!, nserror!) -> nsdata func requesturl(targeturl: string, httpmethod: string, httpbody: string, completion: completionblock){  // request let target = nsurl(string: targeturl) // url let request = nsmutableurlrequest(url: target!) // request  // http-method var method = httpmethod if method != "post" { method = "get" } // standard:     request.httpmethod = method  // http-body let body = httpbody if body != "" {     request.httpbody = body.datausingencoding(nsutf8stringencoding) }  // nsurlsession let session = nsurlsession.sharedsession() let task = session.datataskwithrequest(request, completionhandler: completion) // compiler error! task.resume()  } 

call:

requesturl(targeturl, "get", "", { (responsedata: nsdata!, response: nsurlresponse!, error: nserror!) -> nsdata in          if responsedata != nil {             let resultstring = nsstring(data: responsedata, encoding: nsutf8stringencoding) // nsasciistringencoding             println("data:\n\(resultstring)")          }          if error != nil {             println("error:\n\(error)")         }          return responsedata     }) 

i error @ within func in line 21:

let task = session.datataskwithrequest(request, completionhandler: completion) 

compiler: "cannot invoke 'datataskwithrequest' argument list of type '(nsmutableurlrequest, completionhandler: completionblock)"

as question issue: typealias completionblock = (nsdata!, nsurlresponse!, nserror!) -> nsdata

completion handler returns nsdata shouldn't return in declaration:

func datataskwithrequest(_ request: nsurlrequest,    completionhandler completionhandler: ((nsdata!,                               nsurlresponse!,                               nserror!) -> void)?) -> nsurlsessiondatatask 

this caused type error, because had provided wrong closure type.

and quite reasonable, because datataskwithrequest designed asynchronous. creates http request specified url request object, , calls handler upon completion. if really want make synchronous request can use old nsurlconnection api sendsynchronousrequest, shouldn't it, because synchronous requests very bad design choice: block main ui thread , there no way cancel request except when errors on own. that's why apple created new nsurlsession api, based on completion handlers , deprecated synchronous requests in ios 9.


Comments

Popular posts from this blog

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -