ios - Objective-C: Wait to execute 'While' loop until NSURLConnection request is complete -
basically want way issue nsurlrequest multiple times in loop until condition has been met. using rest api rest api allows maximum of 1,000 results @ time. if have, lets 1,500 total, want make request first 1,000 need rest exact request , except startat: parameter different(so go 1001 - 1500. want set in while loop(while done loading data) , reading semaphores not working out expected to. don't know how many results have until make first request. 50, 1000, or 10,000.
here code:
while(!finishedloadingalldata){ dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); nsurlrequest *myrequest = [self loaddata: startat:startat maxresults:maxresults]; [nsurlconnection sendasynchronousrequest:myrequest queue:[nsoperationqueue mainqueue] completionhandler:^(nsurlresponse *response, nsdata *data, nserror *error) { if(error){ completionhandler(issueswithprojectdata, error); } else{ nsdictionary *issuesdictionary = [[nsdictionary alloc] initwithdictionary:[nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingmutablecontainers error:&error]]; [issueswithprojectdata addobjectsfromarray:issuesdictionary[@"issues"]]; if(issueswithprojectdata.count == [issuesdictionary[@"total"] integervalue]){ completionhandler([issueswithprojectdata copy], error); finishedloadingalldata = yes; } else{ startat = maxresults + 1; maxresults = maxresults + 1000; } } dispatch_semaphore_signal(semaphore); }]; dispatch_semaphore_wait(semaphore, dispatch_time_forever); }
basically want keep while loop waiting until completion block finished. , want while loop check if have of data or not(and if not, make request updated startat value/maxresults value.
right hangs on dispatch_semaphore_wait(semaphore, dispatch_time_forever);
what doing wrong or need do? maybe semaphores wrong solution. thanks.
ok. more look, more don't think bad idea have semaphores solve problem, since other way have serial queue, etc. , solution isn't more complicated.
problem is, requesting completion handler run on main thread
[nsurlconnection sendasynchronousrequest:myrequest queue:[nsoperationqueue mainqueue] completionhandler:^(nsurlresponse *response, nsdata *data, nserror *error)
and creating nsurl request in main thread. hence while waits semaphore released on mainthread, nsurl completion handler waiting mainthread free of current run loop.
create new operation queue.
Comments
Post a Comment