Reputation: 1820
I'm looking to create a simple iOS app that displays the current water level of a local lake. The water level is updated daily on a specific URL. Is it possible to pull content from a webpage using objective c?
Upvotes: 0
Views: 332
Reputation: 24481
Easier way yet using threading:
- (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]);
});
});
}
Upvotes: 1
Reputation: 1254
Absolutely! Use the NSURLConnection object. Use something like the function below, just pass an empty string for 'data' and then parse the HTML returned to find the value you're looking for.
-(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];
}
Upvotes: 1
Reputation: 224844
Sure. Check out the URL Loading System Programming Guide. From that link:
The URL loading system provides support for accessing resources using the following protocols:
- File Transfer Protocol (
ftp://
)- Hypertext Transfer Protocol (
http://
)- Secure 128-bit Hypertext Transfer Protocol (
https://
)- Local file URLs (
file:///
)
Upvotes: 1