ios - NSURLSessionDataTask dataTaskWithURL completion handler not getting called -
i have been learning objective c lately, , decided try connections.
everything great nsurlconnection, until discovered outdated, , tried work nsurlsession.
i trying simple example, can't seem app run code inside completion block.
here code used:
nsurl * url = [nsurl urlwithstring:@"http://api.openweathermap.org/data/2.5/weather?q=london,uk"]; nslog(@"2"); nsurlsessionconfiguration *defaultconfigobject = [nsurlsessionconfiguration defaultsessionconfiguration]; nslog(@"3"); nsurlsession *defaultsession = [nsurlsession sessionwithconfiguration: defaultconfigobject delegate: nil delegatequeue: [nsoperationqueue mainqueue]]; nslog(@"4"); nsurlsessiondatatask * datatask = [defaultsession datataskwithurl:url completionhandler:^(nsdata *data, nsurlresponse *response, nserror *error) { dispatch_sync(dispatch_get_main_queue(), ^{ nslog(@"11"); if(error == nil) { nsstring * text = [[nsstring alloc] initwithdata: data encoding: nsutf8stringencoding]; nslog(@"data = %@",text); } nslog(@"22"); }); }]; nslog(@"5"); [datatask resume]; nslog(@"6");
i numbers printed main execution, completionhandler never executed. tried using delegate, no success.
thanks in advance.
edit suggested, have changed function following:
-(void) doget{ nsurlsessionconfiguration *defaultconfigobject = [nsurlsessionconfiguration defaultsessionconfiguration]; nsurlsession *defaultsession = [nsurlsession sessionwithconfiguration: defaultconfigobject]; nsurlsessiondatatask * datatask = [defaultsession datataskwithurl:[self url] completionhandler:^(nsdata *data, nsurlresponse *response, nserror *error) { nslog(@"11"); if(error == nil) { nsstring * text = [[nsstring alloc] initwithdata: data encoding: nsutf8stringencoding]; nslog(@"data = %@",text); } nslog(@"22"); }]; [datatask resume]; }
my completion manager still not getting run. tried sharedsession instead of passing configuration no luck either.
thanks help
if you're going use completion block rendition of data task, rather specifying delegate
of nil
, this:
nsurlsession *defaultsession = [nsurlsession sessionwithconfiguration: defaultconfigobject delegate: nil delegatequeue: [nsoperationqueue mainqueue]];
you should instead instantiate session using method not take delegate
@ all:
nsurlsession *defaultsession = [nsurlsession sessionwithconfiguration: defaultconfigobject];
or, alternatively, given you're not customizing configuration @ all, can skip instantiation of nsurlsessionconfiguration
altogether , use shared nsurlsession
:
nsurlsession *defaultsession = [nsurlsession sharedsession];
but, bottom line, should not use sessionwithconfiguration:delegate:queue:
rendition unless you're going implement delegates, in case wouldn't use rendition of nsurlsessiondatatask
method completionhandler
parameter.
also, make sure device/simulator running ios 7.0 or greater.
Comments
Post a Comment