开发者

polling an external server from an app when it is launched

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 thi开发者_StackOverflows in iOS? if so how and some sample pieces of code would be much appreciated.

Thanks.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜