polling an external server from an app when it is

2019-08-24 10:52发布

问题:

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.

Thanks.

回答1:

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


标签: ios http ipad