我正在寻找一个简单的iOS应用程序,显示当地湖泊的当前水位。水位每天在特定URL上更新。是否可以使用目标c从网页中提取内容?
答案 0 :(得分:1)
不确定。查看URL Loading System Programming Guide。从那个链接:
URL加载系统支持使用以下协议访问资源:
- 文件传输协议(
ftp://
)- 超文本传输协议(
http://
)- 安全的128位超文本传输协议(
https://
)- 本地文件网址(
file:///
)
答案 1 :(得分:1)
绝对!使用NSURLConnection对象。使用类似下面的函数,只需为'data'传递一个空字符串,然后解析返回的HTML以找到您正在寻找的值。
-(void)sendData:(NSString*)data toServer:(NSString*)url{
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSData *postData = [data dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(conn){
//Connection successful
}
else{
//Connection Failed
}
[conn release];
}
答案 2 :(得分:1)
使用线程的方式更简单:
- (void)viewDidLoad
{
[self contentsOfWebPage:[NSURL URLWithString:@"http://google.com"] callback:^(NSString *contents) {
NSLog(@"Contents of webpage => %@", contents);
}];
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void) contentsOfWebPage:(NSURL *) _url callback:(void (^) (NSString *contents)) _callback {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
dispatch_async(queue, ^{
NSData *data = [NSData dataWithContentsOfURL:_url];
dispatch_sync(dispatch_get_main_queue(), ^{
_callback([[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
});
});
}