编辑:没有按预期工作。请参阅此答案以获得最佳解决方案:Push Notifications
编辑:下一个解决方案仅在用户在应用程序中保持同步时有用。
没有办法在后台永久执行任务,但是您可以使用有限长度的任务来执行此操作,当您创建有限长度时,这将始终在应用程序处于活动状态时运行,但是当您点击主页按钮,ios 只给你 10 分钟来执行你的任务并使其无效,但它让你有机会制作一个“无效处理程序块”,在那里你可以在确定完成之前执行最后的操作。
因此,如果您使用该处理程序块在其他时间调用有限长度的任务,您可以通过运行一个任务 10 分钟来模拟服务,当它结束时,在其他 10 分钟内调用它,因此.
我在创建接口“服务”的项目中使用它。我在这里给你代码:
//
// Service.h
// Staff5Personal
//
// Created by Mansour Boutarbouch Mhaimeur on 30/09/13.
// Copyright (c) 2013 Smart & Artificial Technologies. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Service : NSObject
@property (nonatomic) UIBackgroundTaskIdentifier backgroundTask;
@property (nonatomic) NSInteger frequency;
@property (nonatomic, strong) NSTimer *updateTimer;
- (id) initWithFrequency: (NSInteger) seconds;
- (void) startService;
- (void) doInBackground;
- (void) stopService;
@end
//
// Service.m
// Staff5Personal
//
// Created by Mansour Boutarbouch Mhaimeur on 30/09/13.
// Copyright (c) 2013 Smart & Artificial Technologies. All rights reserved.
//
#import "Service.h"
@implementation Service
@synthesize frequency;
-(id)initWithFrequency: (NSInteger) seconds{
if(self = [super init]){
self.frequency = seconds;
return self;
}
return nil;
}
- (void)startService{
[self startBackgroundTask];
}
- (void)doInBackground{
//Español //Sobreescribir este metodo para hacer lo que quieras
//English //Override this method to do whatever you want
}
- (void)stopService{
[self.updateTimer invalidate];
self.updateTimer = nil;
[[UIApplication sharedApplication] endBackgroundTask:self.backgroundTask];
self.backgroundTask = UIBackgroundTaskInvalid;
}
- (void) startBackgroundTask{
self.updateTimer = [NSTimer scheduledTimerWithTimeInterval:frequency
target:self
selector:@selector(doInBackground)
userInfo:nil
repeats:YES];
self.backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[self endBackgroundTask];
}];
}
- (void) endBackgroundTask{
[self.updateTimer invalidate];
self.updateTimer = nil;
[[UIApplication sharedApplication] endBackgroundTask:self.backgroundTask];
self.backgroundTask = UIBackgroundTaskInvalid;
[self startBackgroundTask];
}
@end
通过这门课我执行我的服务,但我很长时间没有测试它。 我在模拟器中做的最好的测试持续了 16 个小时,一切正常!
编辑:这是在模拟器上测试的,但在应用程序终止后在手机中不起作用。
我举个例子:
// SomeService.h
@interface SomeService : Service
@end
// SomeService.m
#import "SomeService.h"
@implementation SomeService
// The method to override
- (void)doInBackground{
NSLog(@"Background time remaining = %.1f seconds", [UIApplication sharedApplication].backgroundTimeRemaining);
NSLog(@"Service running at %.1f seconds", [self getCurrentNetworkTime]);
}
// Your methods
- (long) getCurrentNetworkTime{
return ([[NSDate date] timeIntervalSince1970]);
}
@end
在您的应用委托或您需要提升服务的地方,您编写下一行:
Service myService = [[SomeService alloc] initWithFrequency: 60]; //execute doInBackground each 60 seconds
[myService startService];
如果你需要阻止它:
[myService stopService];
可能解释得比必要的多,但我想向任何人解释清楚!
我希望它对我的英语有所帮助和抱歉。