ios - method returns before completionhandler -
i developing networkutil project, need method gets url , returns json received url using nsurlsessiondatatask json server. method following:
+ (nsdictionary*) getjsondatafromurl:(nsstring *)urlstring{ __block nsdictionary* jsonresponse; nsurlsession *session = [nsurlsession sharedsession]; nsurlsessiondatatask *datatask = [session datataskwithurl:[nsurl urlwithstring:urlstring] completionhandler:^(nsdata *data, nsurlresponse *response, nserror *error) { jsonresponse = [nsjsonserialization jsonobjectwithdata:data options:0 error:nil]; nslog(@"%@", jsonresponse); }]; [datatask resume]; return jsonresponse; }
the problem completionhandler inside method , method itself run on different threads , in last line jsonresponse nil
how should set jsonresponse returned json urlstring?
best practice issue?
block running in nsurlsession running on different thread - method doesn't wait block finish.
you have 2 options here
first one. send nsnotification
+ (void) getjsondatafromurl:(nsstring *)urlstring{ nsurlsession *session = [nsurlsession sharedsession]; nsurlsessiondatatask *datatask = [session datataskwithurl:[nsurl urlwithstring:urlstring] completionhandler:^(nsdata *data, nsurlresponse *response, nserror *error) { nsdictionary* jsonresponse = [nsjsonserialization jsonobjectwithdata:data options:0 error:nil]; nslog(@"%@", jsonresponse); [[nsnotificationcenter defaultcenter] postnotificationname:@"jsonresponse" object:nil userinfo:@{@"response" : jsonresponse}]; }]; [datatask resume]; }
second one. past completion block utility method
+ (void) getjsondatafromurl:(nsstring *)urlstring completionblock:(void(^)(nsdictionary* response))completion { nsurlsession *session = [nsurlsession sharedsession]; nsurlsessiondatatask *datatask = [session datataskwithurl:[nsurl urlwithstring:urlstring] completionhandler:^(nsdata *data, nsurlresponse *response, nserror *error) { nsdictionary* jsonresponse = [nsjsonserialization jsonobjectwithdata:data options:0 error:nil]; nslog(@"%@", jsonresponse); completion(jsonresponse); }]; [datatask resume]; }
Comments
Post a Comment