Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
752 views
in Technique[技术] by (71.8m points)

iphone - Loading NSData into a UIWebView

In my web browser, I am trying to load a UIWebView with NSData obtained from a NSURLConnection. When I try to load it into the UIWebView, instead of the site, it comes up with the HTML plain text.

Here is my code:

in viewDidLoad:

NSURLRequest *request = [NSURLRequest requestWithURL: [NSURL URLWithString:@"http://www.msn.com"]];
[NSURLConnection connectionWithRequest: request delegate:self];

later in the code:

 -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
  {
     webdata = [NSMutableData dataWithData: data];
  }

 -(void)connectionDidFinishLoading:(NSURLConnection *)connection
  {
    [webview loadData:webdata MIMEType: @"text/html" textEncodingName: @"UTF-8" baseURL:nil];
  }

UIWebView loading plain HTML instead of loading the page

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are not appending data that you are receiving. Use this piece of code

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    if (webdata == nil) {
        webdata = [[NSMutableData alloc] init];
    }
    [webdata appendData:data];
}

This method might be called once or more times depending upon your data length. So instead of assigning new data to your ivar, append your data to it so that you have the full response not the last packet of data received.
------------------------------------------------------------------------------------------------------------------------------------
Updated
Or use like this.

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
        webdata = [[NSMutableData alloc] init];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [webdata appendData:data];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
    [mWebView loadData:webdata MIMEType: @"text/html" textEncodingName: @"UTF-8" baseURL:nil];
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...