泰米尔语艾莉亚,
您不应仅仅因为 AppDelegate 是单例的并且在整个应用程序生命周期中都可用,就将所有代码转储到 AppDelegate 中。将所有内容都放在 appdelegate 中会使您的代码非常笨拙,并遵循非常糟糕的设计模式。
遵循 MVC 是您可以做的一件好事,以保持您的代码可靠和健壮。
无论如何,这就是你可以做的,
我相信你一定有一个singleton 类来进行网络服务调用。如果不创建一个。
例如,我们将类称为WebService.h 和WebService.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
现在您的 Webservice 单例类可以定期访问网络服务器了 :) 现在在您想要开始访问时调用它并在您想要停止它时调用 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];
}
希望对你有帮助