如何反复向后台服务器发送请求?

时间:2012-07-20 11:30:56

标签: iphone objective-c ios

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

提前致谢!

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分:1)

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

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

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