在UIWebView中打开html页面的一部分

时间:2011-09-25 17:46:56

标签: php iphone objective-c uiwebview

人。 我只想加载网页的一部分,但我不能这样做。

来自俄罗斯论坛的人告诉我,我可以使用PHP,但我不能在我的iOS应用程序中创建它。 他发送了这段代码:

>     <?php
>     $url = "http://www.shesterenka.com";
>     $unique_start = "<h1>";
>     $unique_end = "</h1>";
>     function weather($url, $unique_start, $unique_end) {
>     $code = file_get_contents($url);
>     preg_match('/'.preg_quote($unique_start,
>     '/').'(.*)'.preg_quote($unique_end, '/').'/Us', $code, $match);
>     return $match[1];
>     }
>     echo weather($url, $unique_start, $unique_end); ?>

非常感谢。

抱歉我的英语不好。

3 个答案:

答案 0 :(得分:1)

您想在UIWebView上加载哪个部分?如果您知道需要在webView上显示哪些内容,请使用loadHTMLString方法加载。例如:

NSString* content = @"Hello World";
NSString* beforeBody = @"<html><head></head><body>";
NSString* afterBody = @"</body></html>";

NSString* finalContent = [[beforeBody stringByAppendingString:content] 
                                       stringByAppendingString: afterBody];

[webView loadHTMLString:finalContent baseURL:nil];

答案 1 :(得分:1)

这是一个有用的例子。它使用All See Interactive发出HTTP请求。

在头文件中我有:

#import <UIKit/UIKit.h>
#import "ASIHTTPRequest.h"

@interface testViewController : UIViewController <UIWebViewDelegate>{
    UIWebView *webView;
}
@end

在实施文件中我有:

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    webView = [[UIWebView alloc] initWithFrame:CGRectMake(0.0, 0.0, self.view.frame.size.width, self.view.frame.size.height)];

    [webView setDelegate:self];
    [webView setScalesPageToFit:YES];

    NSURL *url = [NSURL URLWithString:@"http://www.shesterenka.com"];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request setDelegate:self];
    [request startAsynchronous];

    self.view = webView;
}


- (void)requestFinished:(ASIHTTPRequest *)request
{
    // Use when fetching text data
    NSString *responseString = [request responseString];

    NSString *unique_start = @"<h1>";
    NSRange i = [responseString rangeOfString:unique_start];

    NSString *unique_end = @"</h1>";
    NSRange j = [responseString rangeOfString:unique_end];

    if(i.location != NSNotFound && j.location != NSNotFound)
    {
        NSString *weather = [responseString substringFromIndex:i.location];
        weather = [responseString substringToIndex:j.location];

        [webView loadHTMLString:weather baseURL:nil];
    } else {
        NSLog(@"strings not found");
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    NSLog(@"Error: %@",error);
}

答案 2 :(得分:0)

这不是加载网页的一部分,它正在加载整个html并返回部分内容。

$code = file_get_contents($url);正在阅读整个网址的HTML。

相关问题