1

在我的应用程序中,我需要在特定时间间隔后向服务器发送请求以获取 xml,例如 1 小时以获取最新数据。我想在后台执行此活动。有人可以建议我如何实现这一点吗?

提前致谢!

4

2 回答 2

2

使用 NSTimer 进行重复请求,如果您想在后台线程中执行请求,您应该执行以下操作:

backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler: ^{
                    [[UIApplication sharedApplication] endBackgroundTask:backgroundTask];
                    backgroundTask = UIBackgroundTaskInvalid;
                 }];


dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    //start url request
});

//after url request complete
[[UIApplication sharedApplication] endBackgroundTask:backgroundTask];
    backgroundTask = UIBackgroundTaskInvalid;
于 2012-07-20T11:40:39.090 回答
1

为了解决上述问题,我创建了 NSOperation 来向服务器发送请求并解析响应。它非常有用并且比使用线程更好。

1.我创建了 NSTimer 实例,它将在特定时间间隔后调用 -(void)sendRequestToGetData:(NSTimer *)timer,如下所示:

//Initialize NSTimer to repeat the process after particular time interval...
    NSTimer *timer = [NSTimer timerWithTimeInterval:60.0 target:self selector:@selector(sendRequestToGetData:) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];

2.然后在 sendRequestToGetData 中,我通过子类化 NSOperation 创建了 NSOperation,如下所示:

-(void)sendRequestToGetData:(NSTimer *)timer
{
    //Check whether user is online or not...
    if(!([[Reachability sharedReachability] internetConnectionStatus] == NotReachable))
    {
        NSURL *theURL = [NSURL URLWithString:myurl];
        NSOperationQueue *operationQueue = [NSOperationQueue new];
        DataDownloadOperation *operation = [[DataDownloadOperation alloc] initWithURL:theURL];
         [operationQueue addOperation:operation];
         [operation release];
    }
}

注意:DataDownloadOperation 是 NSOperation 的子类。

//DataDownloadOperation.h

#import <Foundation/Foundation.h>

@interface DataDownloadOperation : NSOperation
{
    NSURL *targetURL;
}
@property(retain) NSURL *targetURL;
- (id)initWithURL:(NSURL*)url;

@end

//DataDownloadOperation.m
#import "DataDownloadOperation.h"
#import "XMLParser.h"

@implementation DataDownloadOperation
@synthesize targetURL;

- (id)initWithURL:(NSURL*)url
{
    if (![super init]) return nil;
    self.targetURL = url;
    return self;
}

- (void)dealloc {
    [targetURL release], targetURL = nil;
    [super dealloc];
}

- (void)main {

    NSData *data = [NSData dataWithContentsOfURL:self.targetURL];
    XMLParser *theXMLParser = [[XMLParser alloc]init];
    NSError *theError = NULL;
    [theXMLParser parseXMLFileWithData:data parseError:&theError];
    NSLog(@"Parse data1111:%@",theXMLParser.mParsedDict);
    [theXMLParser release];
}

@end
于 2012-07-24T11:56:26.220 回答