ios - Best practice to replace a synchronous NSURLConnection with NSURLSession -
as
nsurlconnection sendsynchronousrequest:returningresponse:error:&connectionerror
is set deprecated have replace importer wrote long time ago.
the importer following:
- it fetches data api-a. data there can on multiple pages.
- it uses data first fetch (also multipage) query data api-b , merges
- results api-b query merged data api-a
i implemented background-operation use methods each api called recursively if there mulitple pages request.
but nsurlsession not support synchronous request see option have lot of overhead (e.g. ivars) control what's called in completion block (e.g. next page or start query api-b).
so, elegant solution bring nsurlsession.
nb: make sure, previous solution not block main thread @ all. easiest way control merge of 2 sources.
this answer not supposed best practice. practical me.
faced situation when bunch of synchronous requests executed in background , order of execution matters i've ended using following:
syncrequestsender.h
#import <foundation/foundation.h> @interface syncrequestsender : nsobject + (nsdata *)sendsynchronousrequest:(nsurlrequest *)request returningresponse:(nsurlresponse **)response error:(nserror **)error; @end
syncrequestsender.m
#import "syncrequestsender.h" @implementation syncrequestsender + (nsdata *)sendsynchronousrequest:(nsurlrequest *)request returningresponse:(nsurlresponse **)response error:(nserror **)error { dispatch_group_t group = dispatch_group_create(); dispatch_group_enter(group); nserror __block *err = null; nsdata __block *data; nsurlresponse __block *resp; [[[nsurlsession sharedsession] datataskwithrequest:request completionhandler:^(nsdata* _data, nsurlresponse* _response, nserror* _error) { resp = _response; err = _error; data = _data; dispatch_group_leave(group); }] resume]; dispatch_group_wait(group, dispatch_time_forever); if (response) { *response = resp; } if (error) { *error = err; } return data; } @end
Comments
Post a Comment