在Foreground中应用程序时每分钟调用一次服务器

时间:2016-06-02 06:45:15

标签: ios objective-c iphone ios7 cocos2d-iphone

我希望每分钟调用我的服务器而app中的前景。这个调用不应该依赖于任何ViewController类作为常用方法。

(例如:调用我的服务器取决于服务器响应,我希望通常显示一些警报)

  

我只是继续尝试app委托方法,但我无法得到任何解决方案。   有没有其他方法或任何方法属于app delegate ??

1 个答案:

答案 0 :(得分:-1)

Tamil_Arya,

您不应该仅仅因为它是单例并且在整个应用程序生命周期中可用而将所有代码转储到AppDelegate中。将所有内容放入appdelegate将使您的代码非常笨拙并遵循非常糟糕的设计模式。

遵循MVC是您可以做的一件好事,以保证您的代码可靠和健壮。

无论如何这是你能做的,

我相信你必须有一个singleton课程来进行网络服务电话。如果没有创建一个。

例如,我们可以将课程称为WebService.hWebService.m

所以你的WebService.h应该是

@interface WebService : NSObject
+ (instancetype)shared; //singleton provider method
- (void)startSendPresence; //method you will call to hit your server at regular interval
- (void)stopSendPresence //method you will call to stop hitting
@end

WebService.m应该看起来像

@interface WebService ()
@property (strong, nonatomic) NSTimer *presenceTimer;
@end

@implementation WebService

+ (instancetype)shared
{
    static id instance_ = nil;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance_ = [[self alloc] init];
    });

    return instance_;
}

- (void)startSendPresence {

    [self sendPresence:nil]; //to make the first webservice call without waiting for timer to trigger

    if(!self.presenceTimer){
        self.presenceTimer = [NSTimer scheduledTimerWithTimeInterval:self.presenceTimerInterval target:self selector:@selector(sendPresence:) userInfo:nil repeats:YES];
    }
}

- (void)sendPresence:(NSTimer *)timer {
    //make your web service call here to hit server
}

- (void)stopSendPresence {
    [self.presenceTimer invalidate];
    self.presenceTimer = nil;
}
@end

现在你的Web服务单例类定期点击网络服务器已经准备好了:)现在当你想要开始点击时调用它,并在你想要停止它时调用stopSendPresence:)

假设你想要在应用程序到达前台时立即开始点击服务器(虽然对我来说没有多大意义,希望它对你有用)

在你的AppDelegate.m

//this method will be called when you launch app
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [[WebService shared] startSendPresence];
}

//this method will be called when you brimg it foreground from background
- (void)applicationWillEnterForeground:(UIApplication *)application {
    [[WebService shared] startSendPresence];
}

如果您想在应用转到后台时立即停止响应服务器

- (void)applicationDidEnterBackground:(UIApplication *)application {
     [[WebService shared] stopSendPresence];
}

希望这有帮助

相关问题