What's the best option for loading web content in a UIWebView?
In previous apps, I've loaded data into a UIWebView using 4 steps: 1. Use an NSURL Connection to grab the data from the web asynchronously 2. WHen the download is complete, convert the NSData object to a string, and manipulate the data prior to display. 3. Write the converted data out to the doc folder 4. Load the data into the UIWebView from the file
But in my current app, I have no need to manipulate the data that I load from the web. I simply want to download asynchronously, and load it into a UIWebView while that view is 开发者_如何学Pythonnot yet visible. Then show that view later, when I need it.
Would it be better to use a loadRequest message that was dispatched as a block to GCD? Is that workable? I'm trying to avoid the whole mess of writing to a local file, then reloading the page from that file. Suggestions?
Why not just give the NSURLRequest
directly to the webview
?
It's perfectly capable of loading data from the web itself if you don't need to massage the data in transit.
Try like this
NSURL *url = [NSURL URLWithString:@"http://www.google.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webview loadRequest:request];
All the best.
UIWebView
You can load the request like @Warrior has mentioned The main advantage is its loaded asynchronously and you don't have to manage everything like @Kevin Ballard has mentioned.
NSURL *url = [NSURL URLWithString:@"http://www.google.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webview loadRequest:request];
UIWebViewDelegate
But if you want to be notified when the url is load completely.You have to conform to the UIWebViewDelegate
Header
@interface YourController : UIViewController <UIWebViewDelegate>
Implementation
1.you have to set the delegate to self
self.yourWebView.delegate = self;
2.you have to implement the following delegate that is where you will be notified when the request loading is completed.
- (void)webViewDidFinishLoad:(UIWebView *)webView {
// Do whatever you want here
}
3.you have to set webview delegate to nil and stop loading the request and to prevent yourself from notorius EXC_BAD_ACCESS Bug due dangling pointer.You can find more about here
// If ARC is used
- (void)dealloc {
[_webView setDelegate:nil];
[_webView stopLoading];
}
// If ARC is not used
- (void)dealloc {
[webView setDelegate:nil];
[webView stopLoading];
[webView release];
[super dealloc];
}
// ARC - Before iOS6 as its deprecated from it.
- (void)viewWillUnload {
[webView setDelegate:nil];
[webView stopLoading];
}
Note:
You should not embed UIWebView objects in UIScrollView objects. If you do so, unexpected behavior can result because touch events for the two objects can be mixed up and wrongly handled.
I hope this covers most needed basic things
精彩评论