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

时间:2011-09-09 20:42:41

标签: ios http ipad

我是iOS的新用户,正在使用在真实设备(iPad)上运行的应用程序。因此,当我在视图可见后在iPad上启动我的应用程序时,应用程序应该能够轮询Web服务器或其他东西(没有任何用户交互)并通过HTTP获取一些信息并根据此信息,我想填写一些文本应用视图中的字段。如果可以在iOS中做这样的事情,你能告诉我吗?如果是这样,那么如何以及一些示例代码将非常受欢迎。

感谢。

1 个答案:

答案 0 :(得分:0)

您可以使用viewWillAppear或viewDidLoad中的NSURLConnection通过http下载信息。在使用NSXMLParser(或iOS的任何其他XML解析器)进行XML解析后下载数据。

//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;
}