我後來是這麼解決不知道行不行,可以長期的在後臺運行
首先我在xx-info.plist 裏的 "Required background modes" 里加入"App provides Voice over IP services"
然後在delegate里加入以下代碼,原理是進入後臺時程序會在600秒那樣結束任務,我做的就是在結束任務前新開一個任務,再結束舊任務,這樣就一直的在後臺運行,希望可能幫助到更多的人,我也查了很久才找到這個方法的。
UIBackgroundTaskIdentifier
backgroundTaskIdentifier; |
02 |
UIBackgroundTaskIdentifier
oldBackgroundTaskIdentifier; |
04 |
-
(BOOL) isMultitaskingSupported{ |
08 |
if ([[UIDevice
currentDevice] |
10 |
respondsToSelector:@selector(isMultitaskingSupported)]){
result = [[UIDevice currentDevice] isMultitaskingSupported]; |
18 |
-
( void )
timerMethod:(NSTimer *)paramSender{ |
20 |
if (count
% 500 == 0) { |
21 |
UIApplication
*application = [UIApplication sharedApplication]; |
25 |
backgroundTaskIdentifier
= [application beginBackgroundTaskWithExpirationHandler:^{ |
29 |
[application
endBackgroundTask:backgroundTaskIdentifier]; |
30 |
oldBackgroundTaskIdentifier
= backgroundTaskIdentifier; |
34 |
-
( void )applicationDidEnterBackground:(UIApplication
*)application |
36 |
if ([self
isMultitaskingSupported] == NO){ |
41 |
backgroundTaskIdentifier
= [application beginBackgroundTaskWithExpirationHandler:^{ |
43 |
oldBackgroundTaskIdentifier
= backgroundTaskIdentifier; |
44 |
if ([self.myTimer
isValid]) { |
45 |
[self.myTimer
invalidate]; |
47 |
self.myTimer
= [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerMethod:) userInfo:nil repeats:YES]; |
50 |
-
( void )applicationWillEnterForeground:(UIApplication
*)application |
52 |
if (backgroundTaskIdentifier
!= UIBackgroundTaskInvalid){ |
53 |
[application
endBackgroundTask:backgroundTaskIdentifier]; |
54 |
if ([self.myTimer
isValid]) { |
55 |
[self.myTimer
invalidate]; |
60 |
-
( void )applicationWillEnterForeground:(UIApplication
*)application |
62 |
if (backgroundTaskIdentifier
!= UIBackgroundTaskInvalid){ |
63 |
[application
endBackgroundTask:backgroundTaskIdentifier]; |
64 |
if ([self.myTimer
isValid]) { |
65 |
[self.myTimer
invalidate]; |