从应用程序启动时轮询外部服务器

我是iOS新手,正在研究在真实设备(iPad)上运行的应用程序。 所以,在视图可见之后,当我在iPad上启动我的应用程序时,应用程序应能够轮询Web服务器或其他内容(无需任何用户交互),并通过HTTP获取一些信息,并基于此信息填写一些文本在应用程序视图中的字段。 你可以让我知道,如果有可能做这样的事情在iOS? 如果是的话,如何和一些样本的代码将不胜感激。

谢谢。

你可以使用viewWillAppear或viewDidLoad中的NSURLConnection通过http下载信息。 下载数据后,如果使用NSXMLParser(或任何其他的iOSparsing器)进行XMLparsing。

//Lets say you have download and process method - (void)downloadAndProcess { //URL you want to download Info from NSURL* url = [NSURL URLWithString:@"http://google.com"]; //Make a mutable url request NSMutableURLRequest* req = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:60]; NSURLConnection* conn = [NSURLConnection connectionWithRequest:req delegate:self]; if(conn) { //NSMutableData receivedData is an instance variable receivedData = [[NSMutableData alloc] init]; } } //NSURLConnection Delegate methods here - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { [receivedData setLength:0]; } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [receivedData appendData:data]; } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { NSLog(@"Error downloading data :%@",[error localizedDescription]); // release receivedData object when connection fails [receivedData release],receivedData = nil; } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { // Connection did finish downloading data which you can process based on what your data is // release receivedData object once you are done processing it. [receivedData release],receivedData = nil; }