开发者

Moving stuff out of appdelegate

I have a tricky situation in my app . i am making the server call in application did finish launching met开发者_JAVA百科hod based on the server response i need to load different views .my app is working fine in simulator but in device the app getting crashed because of the time taking to get the server response .i tried NSThread to run the server call but screen is becoming wait until it gets the response from the server.how can i move the stuff out the app deleagte method


You need to call

[[NSURLConnection alloc]initWithRequest:request delegate:self];

This is asynchronous request, you can implement delegate methods of NSURLConnection in appdelegate.

- (void)connectionDidFinishLoading:(NSURLConnection *)connection;

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;


A better approach would be to display some temporary view and make the network request asynchronous or do it on a background thread. iOS will kill your app if you block the main thread for too long (this may be what's happening in your case), and users aren't likely to want to use an app that spends ten or twenty seconds doing what looks like nothing before putting up a useful display. When you get a response from the server, you can then reconfigure your display appropriately.

BTW, it'd be a good idea to state your question explicitly next time. It's a bit hard to know what you're asking for as the question stands now.


If you're targeting iOS 4.0 and greater, you can use Grand Central Dispatch to make your network call on a background thread. Here's a simple example.

// Create a dispatch queue
dispatch_queue_t networkQueue = dispatch_queue_create("NetworkQueue", 0);

dispatch_async(networkQueue, ^ {
    // Start your network task here.

    // Now when it completes we will dispatch back to the main queue 
    // and you can perform UI updates
    dispatch_async(dispatch_get_main_queue(), ^ {
        // Perform UI updates here on the main thread
    };

    // Release your dispatch queue
    dispatch_release(networkQueue);
};

Now while this is going on be sure you've already put some preliminary unpopulated UI on screen. You should also show and hide UIApplication's networkActivityIndicator appropriately, and possibly some "Loading..." UI.


NSURLConnection is your friend. The best way to solve it is to do the server call asynchronous using NSURLConnection.

There is Sample Code on the Apple Developer Connection that downloads the images for each row in a UITableView asynchronously so the UI is more responsive. So if you take a look at that code you should be able to refactor your code.

Loading the server response asynchronously prevents your app from being shut down by the iOS runtime because you are blocking the main thread for more than 20 seconds.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜