应用程序在前台时每分钟调用一次服务器

Call the server every minute while app in Foreground

我想每分钟调用我的服务器,而 foreground.this 调用中的应用程序不应依赖于任何 ViewController class 作为常用方法。

(例如:调用我的服务器取决于服务器响应我想像往常一样显示一些警报)

i just keep trying by app delegate method but i couldn't get any solution. is there any other ways or any method belongs to app delegate ??

Tamil_Arya,

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

遵循 MVC 是保持代码可靠和健壮的好方法。

无论如何,这是您可以做的,

我相信您一定有 singleton class 来进行网络服务调用。如果没有创建一个。

例如,我们将 class 称为 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 服务单例 class 已准备好定期访问 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];
}

希望对您有所帮助