NSOperation for drawing UI while parsing data? - iphone

Hope you guys can help me :)
In the main thread, I create a NSOperation and add it to a queue.
What that operation do is connect to a data server with NSURLConnection, save the receivedData and parse it.
Operation.m
- (void)start
{
NSLog(#"opeartion for <%#> started.", [cmd description]);
[self willChangeValueForKey:#"isExecuting"];
_isExecuting = YES;
[self didChangeValueForKey:#"isExecuting"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:_url];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"multipart/form-data; boundary=%#", m_BOUNDARY] forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:_postData];
_connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (_connection == nil)
[self finish];
}
Then in this NSURL delegate method I parse the data I've just received from server.
Operation.m
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[self parseItems];
}
In the data, I can found items like, for instance, screenItem, CellItem, TextItem that I send to the main thread for drawing them while arriving. (I create a UITableView if an itemTable arrives, or I create a UIWebView if an itemWeb arrives)
Using this for sending item to main thread:
Operation.m
- (void) parseItems
{
while ([_data length] > 0)
{
NSInteger type = [self _readByte];
switch (type)
{
case SCREEN:
{
[self _send: [self _readScreen]];
break;
}
case CELL:
{
[self _send: [self _readCell]];
break;
}
// ... A lot of different items
}
}
}
- (void)_send:(CItem*)_item
{
[[NSNotificationCenter defaultCenter] postNotificationName:#"newItem" object:_item];
}
Then in notification receiver:
AppDelegate.m
- (void) _newItemArrived:(NSNotification *) notification
{
[self performSelectorOnMainThread:#selector(processItem:) withObject:[notification object] waitUntilDone:NO];
}
My problem is that the UI is not painted until NSOperation finish. I thought that NSOpertion, being a different thread, would not block the main thread, but believe that is what is happening.
Some tips for this issue?
Thanks a lot for reading!

Are you using NSOperationQueue?
Check out this answer to the question NSOperation blocks UI painting? for a simple example of how to update the UI with a notification from an NSOperation running asynchronously on another thread.
UPDATE
NSURLConnection supports asynchronous connections by itself with a delegate. You should use this. If you have specific issue(s), you should describe those.
Check out the ASIHTTPRequest library.
If you really want to use this approach, you could trying running NSURLConnection synchronously (using the class method sendSynchronousRequest:returningResponse:error:). Your app would remain responsive since the connection is on a background thread. However, you would not be able to update anything until all the data is received.

So I know this is a pretty old question but I ran into the same issue and after hours of going through documentation and blogs I found a great solution in this post from Wim Haanstra http://www.depl0y.com/?p=345
Putting your NSOperation in an infinite loop until you get data back should do the trick!

Related

my app hangs when i start downloading using NsurlConnection

I have an app that needs to download a sound file in order to work correctly.
I am using NSURLConnection asynchronously to download my file which is over 20Mb in size.
I placed a progressBarView in order to track the percentage of the downloading and I am using the delegate methods of NSUrlConnection as suggested by Apple.
NSURLRequest *theRequest=[NSURLRequest requestWithURL:soundFileURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0];
// create the connection with the request
// and start loading the data
NSURLConnection *theConnection;
theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
//[theConnection cancel];
//[theConnection start];
if (theConnection) {
// Create the NSMutableData that will hold
// the received data
// receivedData is declared as a method instance elsewhere
receivedData=[[NSMutableData data] retain];
} else {
// inform the user that the download could not be made
}
and delegate methods
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[receivedData appendData:data];
}
and So ...
When I start downloading, the interface hangs from time to time and the progressView hangs as well.
One notable thing, and maybe another question:
I disabled the user interface so the user has to wait until the download finishes and, of course, I give him a message to tell him that.
Would Apple reject my app for that? I am terribly worried about that
Thank you for reading my question :)
NSUrlConnection send events of NSURLConnectionDelegate to main thread by default. You should create new pool and runloop for this connection and be sure that it processed in background. Here are the example of downloading images in background. It using modified NSOperationQueue and NSOperation but you can easy modify it for downloading your file. LinkedImageFetcher on developer.apple.com
//1 First allocate NSOperationQueue object and set number of concurrent operations to execute at a time
NSOperationQueue *thumbnailQueue = [[NSOperationQueue alloc] init];
thumbnailQueue.maxConcurrentOperationCount = 3;
// load photo images in the background
__weak BHCollectionViewController *weakSelf = self;
NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
UIImage *image = [photo image];
dispatch_async(dispatch_get_main_queue(), ^{
// then set them via the main queue if the cell is still visible.
cell.imageView.image = image;
}
});
}];
operation.queuePriority = (indexPath.item == 0) ?
NSOperationQueuePriorityHigh : NSOperationQueuePriorityNormal;
[thumbnailQueue addOperation:operation];
Create Photo class of NSObject and add below method
- (UIImage *)image
{
if (!_image && self.imageURL) {
NSData *imageData = [NSData dataWithContentsOfURL:self.imageURL];
UIImage *image = [UIImage imageWithData:imageData scale:[UIScreen mainScreen].scale];
_image = image;
}
return _image;
}

Cancel ASIFormDataRequest in iOS

Hi. I am uploading images to a server using ASIFormDataRequest. I would like the option to cancel uploading images, so I am attempting to cancel all uploading requests, but it doesn't seem to be working.
Here is my code:
if (asiRequest) {
NSLog(#"cancel call");
[asiRequest cancel];
asiRequest.delegate = nil;
asiRequest.uploadProgressDelegate = nil;
asiRequest = nil;
progressbar.hidden=YES;
uploadinglbl.hidden=YES;
photosCountlbl.hidden=YES;
[self.spinner stopAnimating];
//[self.navigationController popViewControllerAnimated:YES];
}
Can anyone help with how I may be able to cancel all requests?
Thanks in advance.
if(![asiRequest isCancelled]) {
// Cancels an asynchronous request
[asiRequest cancel];
// Cancels an asynchronous request, clearing all delegates and blocks first
[asiRequest clearDelegatesAndCancel];
}

What's the best way to track multiple instances of ASIHTTPRequest?

I have some code that sends multiple ASIHTTPRequests to upload and download data in a view controller. When the view controller gets dealloc'd it should clean up all unfinished requests by setting the delegate to nil.
- (void)viewDidLoad
{
// send multiple requests
[self sendRequest:someURL];
[self sendRequest:someURL];
[self sendRequest:someURL];
[self sendRequest:someURL];
}
- (void)sendRequest:(NSString*)url
{
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
ASINetworkQueue *requestQueue = [ASINetworkQueue queue];
[requestQueue setMaxConcurrentOperationCount:2];
[requestQueue setDelegate:self];
[requestQueue addOperation:request];
[requestQueue go];
}
- (void)dealloc
{
NSLog(#"cancel all operations");
for (ASIHTTPRequest *req in ASIHTTPRequest.sharedQueue.operations)
{
[req cancel];
[req setDelegate:nil];
}
[super dealloc];
}
However, if I pop this view controller before all operations have finished, I get a "message sent to deallocated instance" in ASIHTTPRequest.m complaining that the delegate went away in the code below.
/* ALWAYS CALLED ON MAIN THREAD! */
- (void)reportFailure
{
***crash here --> if (delegate && [delegate respondsToSelector:didFailSelector]) {
[delegate performSelector:didFailSelector withObject:self];
}
if (queue && [queue respondsToSelector:#selector(requestFailed:)]) {
[queue performSelector:#selector(requestFailed:) withObject:self];
}
#if NS_BLOCKS_AVAILABLE
if(failureBlock){
failureBlock();
}
#endif
}
How can I work around this?
You're creating a new queue for each request around this line of code:
ASINetworkQueue *requestQueue = [ASINetworkQueue queue];
So the loop here won't loop over the requests as it's looping over the sharedQueue, not the new one(s) you've created:
for (ASIHTTPRequest *req in ASIHTTPRequest.sharedQueue.operations)
Requests would only get added to the sharedQueue if you use [request startAynchronous] without explicitly setting a different queue.
I may be missing something, but I think waiting until dealloc is too late, you want to cancel your operations on viewWillDisappear or viewDidUnload

UIProgressView, Theading, performSelectorOnMainThread while using ASIHTTPRequest

Kinda stuck on this problem and I'm not sure, where I've gone wrong. Heres what I'm doing:
Class calls:
- (void)updateApplicationDataInBackground {
updateView = [[UpdatingView alloc] init];
[self.view addSubview:updateView.view];
DataSynchronizer *dataSynchronizer = [[DataSynchronizer alloc] init];
[NSThread detachNewThreadSelector:#selector(initWithDataRequest:) toTarget:dataSynchronizer withObject:self];
[dataSynchronizer release];
This creates a thread to retrieve data from the server and parse it. In DataSynchronizer this is the method being called:
- (void)initWithDataRequest:(id)parent {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
controller = parent;
NSLog(#"DataSynchronizer initWithDataRequest called");
NSURL *url = [NSURL URLWithString: ApiUrl];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:ApiKey forKey:#"key"];
[request setPostValue:ApiPass forKey:#"password"];
[request setPostValue:#"somevalue" forKey:#"framework"];
[request setPostValue:#"somevalue" forKey:#"method"];
[request setDidFinishSelector:#selector(parseResult:)];
[request setDidFailSelector:#selector(requestError:)];
[request setTimeOutSeconds:60];
[request setDelegate:self];
[request startAsynchronous];
[pool release];
After my data is received I parse the contents and do my data synch. This is all working as expected. I've decided to throw in a UIProgressView so the user can see what is going on with this request, this progress view lives in updateView which is created in the updateApplicationDataInBackground.
I'm not trying to show progress for the web service call but simply when milestones are reached in the data processing. In the DidFinishSelector its calling parseResult
There are five method its calls with the response data:
[self parseData:[data objectForKey:#"types"] forObject:[Types class] andParent:nil];
[controller performSelectorOnMainThread:#selector(updateProgress:) withObject:[NSNumber numberWithFloat:.4] waitUntilDone:YES];
After each process I'm trying to update the UIProgressView, it will never update. Now if I simply call performSelectorOnMainThread from outside the ASIHTTPRequest it works as expected, but not within the DidFinishSelector. I've tried many variations on this where it calls a local method which updates the mainThread, where I simply use performSelector. Nothing works, how do I update the the UIProgessView?
Is the problem a thread spawning a thread?
Thanks
EDIT:
Looks like the DidFinishSelector is being called on the main thread already. I've updated my code to simply call:
[controller updateProgress:[NSNumber numberWithFloat:.8]]
Still no luck....
Realized it might be helpful to see the UIProgessView update method.
- (void)updateProgress:(NSNumber *)progress {
float newProgess = [progress floatValue];
[updateView.myProgress setProgress: newProgess];
Ok so it looks like I found my own answer after changing somethings around. Because ASIHttpRequest performs SetDidFinish selector on the main thread my calls performSelectorOnMainThread weren't doing anything. I changed my initial call for the DataSynchronizer to the main thread and added changed the DidFinish method to:
- (void)parseDataInBackground:(ASIHTTPRequest *)request {
[NSThread detachNewThreadSelector:#selector(parseResult:) toTarget:self withObject:request];
Which then makes the parse method run on separate thread (since its the bulk of the processing and now performOnMainThread works without issue.

NSOperationQueue and ASIHTTPRequest

I'm writing test cases for a wrapper class written around ASIHTTPRequest. For reasons I can't determine, my test cases complete with failure before the ASIHTTPRequest finishes.
Here's how the program flow works.
Start in my test case.
Init my http engine object, instruct it to create a new list
Create the new ASIHTTPRequest object and set it up.
Add the request to an operation queue.
Wait until that queue is empty
Check to see if my delegate methods were called and fail the test if they weren't.
Now, most of the time everything works fine and the test passes, but some of the time it fails because my delegate methods were called AFTER the operation queue returned control to my wait method.
Test Case
// Set my flags to 'NO'
- (void)setUp {
requestDidFinish = NO;
requestDidFail = NO;
}
- (void)testCreateList {
NSString *testList = #"{\"title\": \"This is a list\"}";
JKEngine *engine = [[JKEngine alloc] initWithDelegate:self];
NSString *requestIdentifier = [engine createList:jsonString];
[self waitUntilEngineDone:engine];
NSString *responseString = responseString_;
[engine release];
GHAssertNotNil(requestIdentifier, nil);
GHAssertTrue(requestDidFinish, nil);
GHAssertTrue([responseString hasPrefix:#"{\"CreateOrEditListResult\""], nil);
}
// Puts the test into a holding pattern until the http request is done
- (void)waitUntilEngineDone:(JKEngine *)engine {
[engine waitUntilFinishedRunning];
}
// The delegate method called on successful completion
- (void)requestFinished:(NSString *)requestIdentifier withResponse:(NSString *)response {
NSLog(#"request did finish");
requestDidFinish = YES;
responseIdentifier_ = [requestIdentifier retain];
responseString_ = [response retain];
}
Engine Code
- (NSString *)createList:(NSString *)list {
ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request addRequestHeader:#"Content-Type" value:kContentType];
[request setRequestMethod:kPOST];
request.delegate = self;
[request appendPostData:[list dataUsingEncoding:NSUTF8StringEncoding]];
NSString *requestIdentifier = [NSString stringWithNewUUID];
[operationQueue_ addOperation:request];
[operationDictionary_ setObject:request forKey:requestIdentifier];
return requestIdentifier;
}
// This is the ASIHTTPRequest delegate method that's called on success
// but it sometimes isn't called until AFTER the operationQueue finishes running
- (void)requestFinished:(ASIHTTPRequest *)request {
DLog([request responseString]);
BOOL canNotifiyDelegate = [self.delegate respondsToSelector:#selector(requestFinished:withResponse:)];
if (canNotifiyDelegate) {
NSArray *keyArray = [operationDictionary_ allKeysForObject:request];
NSString *requestIdentifier = [keyArray objectAtIndex:0];
[operationDictionary_ removeObjectForKey:requestIdentifier];
if ([keyArray count] != 1) {
ALog(#"It looks like a request was added to the operation dictionary multiple times. There's a bug somewhere.", nil);
}
[self.delegate requestFinished:requestIdentifier withResponse:[request responseString]];
}
}
- (void)waitUntilFinishedRunning {
[operationQueue_ waitUntilAllOperationsAreFinished];
}
This is the way ASIHTTPRequest works. Delegate methods are called on the main thread, and calls to delegates do not block the request thread, so it's perfectly possible your delegates will be called after the queue finishes.
ASIHTTPRequest calls delegate methods on the main thread, by default GH-Unit runs its tests on a background thread. I'm still a little hazy on exactly what was going on, but forcing my network tests to run on the main thread fixed the problem.
I implemented the following method in my network test class.
- (BOOL)shouldRunOnMainThread {
return YES;
}