我正在尝试做的是一个在呼叫进入时运行代码的应用。我知道我无法获得调用者的任何细节,这很好。
到目前为止,我的问题是它只在应用程序位于前台时才有效。
这是我的代码:
#import <CoreTelephony/CoreTelephonyDefines.h>
#import <CoreTelephony/CTCallCenter.h>
#import <CoreTelephony/CTCall.h>
CTCallCenter *callCenter = [[CTCallCenter alloc] init];
[callCenter setCallEventHandler:^(CTCall *call) {
ONLog(@"Event handler called");
if ([call.callState isEqualToString: CTCallStateConnected]) {
ONLog(@"Connected");
} else if ([call.callState isEqualToString: CTCallStateDialing]) {
ONLog(@"Dialing");
} else if ([call.callState isEqualToString: CTCallStateDisconnected]) {
ONLog(@"Disconnected");
} else if ([call.callState isEqualToString: CTCallStateIncoming]) {
ONLog(@"Incomming");
}
}];
有人可以帮助我将此次运行作为后台任务吗?
编辑:
我使用了Richas这样的代码:
__block UIBackgroundTaskIdentifier yourBackgroundTaskName;
yourBackgroundTaskName = [application beginBackgroundTaskWithExpirationHandler:^{
// CODE FOR EXPIRATION HANDLER BLOCK
[application endBackgroundTask: yourBackgroundTaskName];
yourBackgroundTaskName = UIBackgroundTaskInvalid;
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// DO YOUR STUFF HERE. START OF BACKGROUND TASK.
NSLog(@"Background time Remaining: %f",[[UIApplication sharedApplication] backgroundTimeRemaining]);
self.callCenter = [[CTCallCenter alloc] init];
[self.callCenter setCallEventHandler:^(CTCall *call) {
ONLog(@"Event handler called");
if ([call.callState isEqualToString: CTCallStateConnected]) {
ONLog(@"Connected");
} else if ([call.callState isEqualToString: CTCallStateDialing]) {
ONLog(@"Dialing");
} else if ([call.callState isEqualToString: CTCallStateDisconnected]) {
ONLog(@"Disconnected");
} else if ([call.callState isEqualToString: CTCallStateIncoming]) {
ONLog(@"Incomming");
}
}];
//WHEN YOU ARE DONE WITH YOUR TASK, TELL THAT TO SYSTEM
[application endBackgroundTask: yourBackgroundTaskName];
yourBackgroundTaskName = UIBackgroundTaskInvalid;
});
答案 0 :(得分:2)
您应该检查以下两种方法来解决您的问题:
- (UIBackgroundTaskIdentifier)beginBackgroundTaskWithName:(NSString *)taskName expirationHandler:(void (^)(void))handler`
- (UIBackgroundTaskIdentifier)beginBackgroundTaskWithExpirationHandler:(void (^)(void))handler
您可以在applicationDidEnterBackground
&amp;可以给你买一些时间(5-10分钟)。代码可能如下所示:
- (void)applicationDidEnterBackground:(UIApplication *)application
{
UIBackgroundTaskIdentifier yourBackgroundTaskName;
yourBackgroundTaskName = [application beginBackgroundTaskWithExpirationHandler:^{
// CODE FOR EXPIRATION HANDLER BLOCK
[application endBackgroundTask: yourBackgroundTaskName];
yourBackgroundTaskName = UIBackgroundTaskInvalid;
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// DO YOUR STUFF HERE. START OF BACKGROUND TASK.
//WHEN YOU ARE DONE WITH YOUR TASK, TELL THAT TO SYSTEM
[application endBackgroundTask: yourBackgroundTaskName];
yourBackgroundTaskName = UIBackgroundTaskInvalid;
});
}
希望,这至少应该让你开始。