在应用程序启动时从应用程序轮询外部服务器 [英] polling an external server from an app when it is launched

查看:103
本文介绍了在应用程序启动时从应用程序轮询外部服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to iOS and working on an app which runs on a real device (iPad). So, when I launch my app on the iPad after the view is visible, the app should be able poll a web server or something (without any user interaction) and get some information over HTTP and based on this information, I want fill some text fields in the app view. can you let me know if it is possible to do something like this in iOS? if so how and some sample pieces of code would be much appreciated.

谢谢。

推荐答案

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

You can download information over http using NSURLConnection in the viewWillAppear or viewDidLoad. After download the data if its XML parse using NSXMLParser (or any other XML parser for iOS).

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

这篇关于在应用程序启动时从应用程序轮询外部服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆