Cocoa Touch begin command AFTER viewDidLoad - iphone

I have an application in which I am required to connect to the internet after a view is loaded. However, if I put this code in the viewDidLoad method the parent view freezes, and then unfreezes after the connection onto the new view. However, I would like the new view to load FIRST, and then to start the connection. I tried using viewDidAppear:, however I am getting the same issue.
Also, will any animations continue playing during the connection? Will the UI be responsive? If not, is multithreading the way to go?
Here is some of my code:
-(void)viewDidLoad {
[super viewDidLoad];
//Do some other view initialization
//Connect is a class I use to connect to the internet
[Connect getData:someString];
}
When I put the code in viewDidAppear the same thing happens.
Connection code:
NSMutableURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
NSHTTPURLResponse *response;
NSError *error;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
Also, I forgot to mention that I am running a regular expression as well after the connection.

As the name of the method says, the view has already been loaded when viewDidLoad executes.
Generally, be sure to use asynchronous connections to connect to the internet. Never block the main thread.

it is easier than you may think.
All you need is some thread management. On the view did Do:
[NSThread detachNewThreadSelector:#selector(yourMethod:) toTarget:yourTarget withObject:yourObject];
and later in another part do:
- (void)yourMethod:(id)sender{
//download the info but do not update the GUI
[self performSelectorOnMainThread:#selector(updatingTheGUI:) withObject:yourObject waitUntilDone:NO]
}
- (void)updatingTheGUI:(id)sender{
//Update your GUI
}

You will notice that the viewDidLoad method documentation of UIViewController states:
...Called after the controller’s view is loaded into memory.
This doesn't necessarily mean that it's called after the view is displayed on screen.
To answer your other questions, if you make your network request the way you have described, no, animations will not continue playing while the request is in progress and no, you can't guarantee that the UI will be responsive. This is because the network request will take an unknown amount of time. Therefore, if you make the request on the main thread, the main thread will be blocked for that period of time, however long it takes.
And, as for the last question, is multithreading the way to go? As others have stated, the easiest and probably most popular way of handling this is to initialize the NSURLConnection with initWithRequest:delegate:. The delegate being your UIViewController or Connect class, or whatever class you want to conform to the NSURLConnectionDelegate protocol and use the NSURLConnectionDelegate methods to process the downloaded data. NSURLConnection will do the work asynchronously and keep the main thread free to handle animations, displaying the UI, etc.

I know it sounds a bad idea for your app. performance but try giving a delay or sleep in between to check if it works that way. Later try to implement the asynchronous call as someone earlier stated..

Related

Moving NSURLConnection methods to reusable class

I am using NSURLConnection to download some JSON from a webservice, and then display in a UITableView. I have all the code working well in the view class, but I wondered if I could have the NSURLConnection methods available to other classes?
For example, something like the following:
NSURLConnectionClass *connection = [[NSURLConnectionClass alloc] init];
NSArray *myDataArray = [connection withURL: [NSURL URLWithString: #"http://www.example.com"]];
// Reload table with new data
I realise this wont work as NSURLConnection is asynchronous, but wondered if there was something else I could try. I'm basically trying to avoid repeating code in every view that downloads data.
You can create a delegate protocol for your custom connection class. This way it can download async and still and call back when done. Even better would be to use blocks for callbacks. This pattern is used in the popular ASIHttpRequest class.
You can even make this class the delegate and data source for the table view. This way you only have to call [tableview reloadData] when done loading. Downside is that this mixes up the MVC pattern a bit.

vs. [UIWebView loadRequest:] - optimizing return from iAD to a view with a UIWebView

I have a view that includes a UIWebView as well as an iAD AdBannerView.
To optimize the experience and reduce bandwidth contention - I suspend the UIWebView's network activity when the iAd "detail view" is being loaded and resume it when the user returns from the ad. Currently, I simply do the following:
-(BOOL)bannerViewActionShouldBegin:(ADBannerView *)banner willLeaveApplication:(BOOL)willLeave
{
if (self.webView.loading) {
[self.webView stopLoading];
self.loadingWasInterrupted = TRUE;
}
return YES;
}
-(void)bannerViewActionDidFinish:(ADBannerView *)banner
{
if (self.loadingWasInterrupted) {
//Should use loadRequest: instead?
[self.webView reload];
}
}
I'm trying to understand if it there is any difference between calling reload vs. loadRequest: a second time, and if so, which is more efficient.
I'm guessing reload simply just saves you having to hold onto the request object and really does the same thing but I'd like to know for sure. The docs and header don't offer any clue.
I understand I could pick apart the network activity to understand what's happening but would appreciate any insight from someone who has looked at this before or who generally understands if reload behavior differs from loadRequest at all. Thank you.
Okay, a fairly complicated solution but never the less one that I think might work for you:
Define a custom protocol handler for http:
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html#//apple_ref/doc/uid/10000165i
Using NSURLProtocol as the subclass. The handler will start a NSURLConnection, and return the data as it comes in to the client (in this case this will be the UIWebView that initiated the connection). Have it add itself as an observer to NSNotificationCenter for a "Pause" notification.
When you would like to display an iAd, you can send your pause notification, this will cancel the NSURLConnection (but not the NSURLProtocol, which will remain open and loading, and thus your webview will continue to appear as if it were loading).
Then when the add is finished you can send a "resume" notification (much the same), except in this case any active NSURLProtocol handlers receiving the notification will create new NSURLConnections, using the Range: header to resume where they left off:
iphone sdk: pausing NSURLConnection?
Some caveats:
Only will work when browsing websites that support the resume header (otherwise you might have to start the connection anew, and just ignore data prior to the latest byte received).
Your NSURLRequests should be formed so that they don't have a timeout. (if you want a timeout then it should be in the NSURLProtocol handlers NSURLConnections).
I'm guessing here, but I believe the reload is doing a loadRequest: internally. If you are really intent on testing this you cold add a temporary subclass to UIWebView and override the reload and loadRequest methods just for the sake of logging.
- (void)reload
{
NSLog(#"reload called");
[super reload];
}
- (void)loadRequest:(NSURLRequest *)request
{
NSLog(#"loadRequest called");
[super loadRequest:request];
}
When you call the method "loadRequest", you call it like
[webview loadRquest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.ururl.com"]]];
But when u call "reload", u just instruct to reload whatever the current request is.
So basically in latter case , u are saving urself from creating a url from string and then a request from url and that makes it pretty convenient for use.
As per case of functionality, reload itself calls loadRequest so basically there is no difference in terms of efficiency and even in speed.
However basically for ur case and in many of my cases , the thing which we want but Apple has not given us is something like:-
[webview pauseLoading];
[webview resumeLoading];
So to sum up the whole thing , use any of them but if u r lazy like me to again specify the urlrequest just use "reload"
Apologies
Sorry guys I used to think that reload must be calling loadRequest but when I tried NWCoder's method, it doesnot call loadRequest on calling reload. But I still think reload and loadRquest follows the same method for loading the page

NSThread terminating too early

I have an app that uploads to Google Spreadsheets via the GData ObjC client for Mac/iPhone. It works fine as is. I'm trying to get the upload portion on its own thread and I'm attempting to call the upload method on a new thread.
Look:
-(void)establishNewThreadToUpload {
[NSThread detachNewThreadSelector:#selector(uploadToGoogle) toTarget:self withObject:nil];
}
-(void)uploadToGoogle {
NSAutoReleasePool *pool = [[NSAutoReleasePool alloc] init];
//works fine
[helper setNewServiceWithName:username password:password];
//works fine
[helper fetchUserSpreadsheetFeed];
//inside the helper class, fetchUserSpreadsheet feed calls ANOTHER method, which
//calls ANOTHER METHOD and so on, until the object is either uploaded or fails
//However, once the class gets to the end of fetchUserSpreadsheetFeed
//control is passed back to this method, and
[pool release];
//is called. The thread terminates and nothing ever happens.
}
If I forget about using a separate thread, everything works like it's supposed to. I'm new to thread programming, so if there's something I'm missing, please clue me in!
Thanks!
I've had this problem and I have a solution, however, the solution kind of makes me cringe as it works, but something smells about it... it seems like their should be a better way.
I suspect somewhere within [helper fetchUserSpreadsheetFeed] you are using some form of NSURLConnection. If you are using an asynchronous http request (where you setup the delegate for callback functions and such) the thread may terminate before the connection has a chance to invoke those callback functions and silently fail. Here's my solution which keeps the thread alive until the callbacks set a 'finished' variable to YES. (I also seem to have trouble posting code in these text boxes so if those angels that run around editing stuff can help me out that'd be great!)
- (void)fetchFeed {
//NSLog(#"making request");
[WLUtilities makeHttpRequest:self.feedUrlString withHttpHeaders:nil withDelegate:self];
//block this thread so it's still alive when the delegates get called
while(!finished) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
}
The problem I have with this solution is that spinning while loops are generally not good practice. I'm not sure as to the nature of the runloop business though, it may be properly sleeping and stuff but I'm not sure.
At any rate, you could give that a try and see what happens!
NOTE: my "WLUtilities" function is just a wrapper around the NSURLConnection function to create an asynchronous http request. Another solution you might try is simply using a synchronus request but I don't like this solution much either because the asynchronous call offers finer grained control over the connection.
Use the techniques in this answer:
How can I upload a photo to a server with the iPhone?

Stop lazy-loading images?

Here's the issue – I followed along with the Apple lazy-load image sample code to handle my graphical tables. It works great. However, my lazy-load image tables are being stacked within a navigation controller so that you can move in and out of menus. While all this works, I'm getting a persistent crash when I move into a table then move immediately back out of it using the "back" button. This appears to be a result of the network connections loading content not being closed properly, or calling back to their released delegates. Now, I've tried working through this and carefully setting all delegates to nil and calling close on all open network connections before releasing a menu. However, I'm still getting the error. Also – short posting my entire application code into this post, I can't really post a specific code snippet that illustrates this situation.
I wonder if anyone has ideas for tasks that I may be missing? Do I need to do anything to close a network connection other than closing it and setting it to nil? Also, I'm new to debugging tools – can anyone suggest a good tool to use to watch network connections and see what's causing them to fail?
Thanks!
Have you run it through the debugger (Cmd-Y)? Does it stop at the place where the crash is happening? That should show you in code where the issue is happening. I'm betting the issue has to do with over-releasing something rather than cleaning up connections. Are you getting EXC_BAD_ACCESS? Check any delegates and make sure they are nil when -viewWillDisappear gets called. That way, if anything tries to call back to a delegate, it will just be a no-op.
You may also want to try enabling zombies (NSZombieEnabled) which will tell you when an object that has been released is being accessed again. It's very helpful in finding over-released objects.
Ah ha... after a large zombie hunt (thanks, Matt Long), I discovered that the issue stems from an error in Apple's LazyTableImages sample code. That example provides the following implementation for canceling all image loads, which I turned into a general-purpose stopAllImageLoads method...
From RootViewController.m in LazyTableImages sample code:
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// terminate all pending download connections
NSArray *allDownloads = [self.imageDownloadsInProgress allValues];
[allDownloads performSelector:#selector(cancelDownload)];
}
There is in error in the last line of the above method where performSelector is called on an array of objects. The above implementation calls the selector on the array itself, rather that on each object in the array. Therefore, that last line should be this:
[allDownloads makeObjectsPerformSelector:#selector(cancelDownload)];
Once that line was changed, everything else fell into place. It turns out I wasn't calling my stopAllImageLoads method where I meant to – I had disabled it at one point because it was causing an error. Once that was back in place, the memory issues cleared up because image loads were successfully canceled before the table delegate was released.
Thanks all for your help.
If you're doing ANY asynchronous function (network requests, Core Location updates, etc), you run the risk that your view controller that is the delegate of that action is deallocated by the time the async function returns. i.e. you back out of the view and take the delegate target away from the background process. I've dealt with this several times.
Here's what you do. Use the ASIHTTPRequest library (which you should be doing anyway--it's brilliant). Create a synthesized property to hold your request. Then in viewWillDisappear, call -cancel on your request. To be safe, I also set its delegate to nil, but that should be unnecessary.
Here's a sketch of what you want to do. Note I typed this right here, haven't syntax-checked it or anything.
#implementation MyViewController
#synthesize req //this is an ASIHTTPRequest *req.
-(void)viewDidLoad
{
//make an NSURL object called myURL
self.req = [ASIHTTPRequest requestWithURL:myURL];
self.req.delegate = self;
[self.req startAsynchronous];
}
-(void)viewWillDisappear
{
[self.req cancel];
}
-(void)requestFinished:(ASIHTTPRequest *)request
{
NSString *string = [request responseString];
}

delay loading of UIWebView in UITabBar app

I have an UITabBar based iPhone app with 4 different UIWebViews under every tab. Right now all the UIWebViews load on startup and it takes a little bit too long.
I would like to load the default tab's UIWebView first, then load the others in the background. What is the best way to do this?
I have seperate ViewControllers set up for each tab and have this in every .m file:
- (void)viewDidLoad {
NSString *urlAddress2 = #"http://google.com ";
//Create a URL object.
NSURL *url2 = [NSURL URLWithString:urlAddress2];
//URL Requst Object
NSURLRequest *requestObj2 = [NSURLRequest requestWithURL:url2];
//Load the request in the UIWebView.
[webView2 loadRequest:requestObj2];
}
Is there a simple way to tell the other 3 tabs to start loading a few seconds after launch instead of at launch? Would that be a good idea?
Thanks a lot!
I've gotten around this issue by implementing a model layer through which all requests pass. Requests are queued and serviced in priority order, generally one at a time. I've added specific methods to allow a controller to escalate the priority of requests so that, if necessary, two or more requests will be active at once. When a request finishes, it alerts it delegate (the WebView's controller) that data is ready to be loaded.
Depending on how you want to set things up, you can put a callback in "webViewDidFinishLoad" (or, perhaps, shouldStartLoadWithRequest or webViewDidStartLoad) that triggers the model layer to dequeue and service the next request. For safety, you'll also want a timeout in the model layer.
Note: you'll also need to add some custom code into shouldStartLoadWithRequest to differentiate between clicks and the model layer pushing data in. I.e. you'll want to return NO or YES depending on the navigationType.
If you use ASIHTTPRequest instead of NSURLRequest, you can fire a synchronous request for the first URL. Once that request is complete, you can then fire off the other three URL requests asynchronously (i.e., in the background).
You can use NSTimer, or do the loading in viewDidAppear or similar.
Use viewDidAppear. This will be sent to the controller after the view fully appears and animations end.