0

我正在创建一个将继续在后台运行的应用程序。当设备连接到 MAC 并调试时,但当我断开连接并独立运行应用程序时,它将在 10 分钟内完成。是否有任何设置或我的编码错误?

我的代码是 appdeledate.h 是

#import <UIKit/UIKit.h>
#import <GameKit/GameKit.h>


@class TashouNoEnViewController;

@interface TashouNoEnAppDelegate : NSObject <UIApplicationDelegate,GKSessionDelegate,GKPeerPickerControllerDelegate> {
    UIWindow *window;
    TashouNoEnViewController *viewController;
    GKSession *mySession;
    IBOutlet UITextField *messageTextField;
    UIBackgroundTaskIdentifier backgroundTaskIdentifer;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet TashouNoEnViewController *viewController;

@property (nonatomic, retain) IBOutlet UINavigationController *navigationController;
@end

appdelegate.M 是

#import "TashouNoEnAppDelegate.h"
#import "TashouNoEnViewController.h"
#define kSessionID @"_tashounoen"

@implementation TashouNoEnAppDelegate

@synthesize window;
//=_window;
@synthesize viewController;
@synthesize navigationController=_navigationController;

NSString *message102;

NSString* a_home_dir;
NSString* a_doc_dir;
NSString* a_path;
NSString *switchcheck;
NSInteger myselfint;
NSInteger swithchcheckint;
NSInteger runcount;
NSInteger runcount2;
NSInteger totalruncount;
UIBackgroundTaskIdentifier bgTask;
NSTimer *caallTimer;
NSTimer *caallTimer2;
 NSString *message100;
 NSString *message200;

- (void)applicationDidFinishLaunching:(UIApplication *)application {    

    // Override point for customization after app launch    
    [window addSubview:viewController.view];
    [window makeKeyAndVisible];
}


- (void)dealloc {
    [viewController release];
    [window release];
    [super dealloc];
}


- (void)applicationWillResignActive:(UIApplication *)application
{
 /**
    NSLog(@"applicationWillResignActive");
    // NSLog(@"%s", __PRETTY_FUNCTION__);
    UIApplication* app = [UIApplication sharedApplication];
    NSAssert(backgroundTaskIdentifer == UIBackgroundTaskInvalid, nil);
    backgroundTaskIdentifer = [app beginBackgroundTaskWithExpirationHandler:^{

        //  NSLog(@"expired!");
        dispatch_async(dispatch_get_main_queue(), ^{
            if (backgroundTaskIdentifer != UIBackgroundTaskInvalid) {
                [app endBackgroundTask:backgroundTaskIdentifer];
                backgroundTaskIdentifer = UIBackgroundTaskInvalid;
            }
        });
    }];
    **/
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    self.window.rootViewController = self.navigationController;
    runcount=0;
    totalruncount=0;
    NSLog(@"applicationDidEnterBackground");
   caallTimer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(CAALL2) userInfo:nil repeats:NO];

    void (^handler)(void)  = ^{
            bgTask = UIBackgroundTaskInvalid;
    };
   bgTask = [application beginBackgroundTaskWithExpirationHandler:handler];
    [application setKeepAliveTimeout:600 handler:^{


         bgTask = [application beginBackgroundTaskWithExpirationHandler:handler];
        [caallTimer invalidate];
        caallTimer = nil;

        caallTimer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(CAALL2) userInfo:nil repeats:NO];


    }];

}

- (void)applicationWillEnterForeground:(UIApplication *)application
{


    NSLog(@"applicationWillEnterForeground");
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{


    NSLog(@"applicationDidBecomeActive");
}

- (void)applicationWillTerminate:(UIApplication *)application
{


    NSLog(@"applicationWillTerminate");
}

- (void)session:(GKSession *)session connectionWithPeerFailed:(NSString *)peerID withError:(NSError *)error {
}

- (void)session:(GKSession *)session didFailWithError:(NSError *)error {

}

- (void)session:(GKSession *)session didReceiveConnectionRequestFromPeer:(NSString *)peerID {

    NSError *error;
    if(![mySession acceptConnectionFromPeer:peerID error:&error]) {
    } else {

    }
}


-(void)CAALL2

{


            [mySession disconnectFromAllPeers];
            [mySession release];
            mySession = nil;
            mySession = [[GKSession alloc] initWithSessionID:kSessionID displayName:nil sessionMode:GKSessionModePeer];
            mySession.delegate = self;
            [mySession setDataReceiveHandler:self withContext:nil];
            mySession.available = YES;

caallTimer = [NSTimer scheduledTimerWithTimeInterval:500 target:self selector:@selector(CAALL2) userInfo:nil repeats:NO];
  //  if (totalruncount<21){

  //  }

}
- (void)session:(GKSession *)session peer:(NSString *)peerID didChangeState:(GKPeerConnectionState)state {
    switch (state) {
        case GKPeerStateAvailable:
            NSLog(@"GKPeerStateAvailable");
            [mySession connectToPeer:peerID withTimeout:31.0f];
            break;
        case GKPeerStateUnavailable:
            break;
        case GKPeerStateConnected:
            [self btnSend:peerID];
   break;
        case GKPeerStateDisconnected:
            break;
        case GKPeerStateConnecting:
            break;
        default:
            break;
    }
}

- (void) receiveData:(NSData *)data fromPeer:(NSString *)peer inSession:(GKSession *)session context:(void *)context {


    message100 = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
 //   NSLog(@"frompeerid%@",peer);
 //   NSLog(@"get%@",message100);
    int checkdata = [message100 intValue ];
    if (checkdata==111)
    {
        message100 =@"111";
        UIApplication *app  = [UIApplication sharedApplication];
        UILocalNotification *notification = [[UILocalNotification alloc] init];
        NSDate *notificationDate = [NSDate dateWithTimeIntervalSinceNow:0];
        notification.soundName = UILocalNotificationDefaultSoundName;
        notification.fireDate  = notificationDate;
        notification.timeZone  = [NSTimeZone systemTimeZone];
        notification.alertBody = message100;
        [app scheduleLocalNotification:notification];
        [notification release];
    }
    else if (checkdata==110)
    {
        message100 =@"110";
        UIApplication *app  = [UIApplication sharedApplication];
        UILocalNotification *notification = [[UILocalNotification alloc] init];
        NSDate *notificationDate = [NSDate dateWithTimeIntervalSinceNow:0];
        notification.soundName = UILocalNotificationDefaultSoundName;
        notification.fireDate  = notificationDate;
        notification.timeZone  = [NSTimeZone systemTimeZone];
        notification.alertBody = message100;
        [app scheduleLocalNotification:notification];
        [notification release];
    }

}

- (void) mySendDataToPeers:(NSData *) data:(NSString *)peerID
{
    NSError* error = nil;
    NSLog(@"senddata");
    if (mySession)
       NSLog(@"mypeerid%@",peerID);

                [mySession sendData:data toPeers:[NSArray arrayWithObject:peerID] withDataMode:GKSendDataReliable error:&error];
    if (error) {
        NSLog(@"%@", error);
    }
}


-(void) btnSend:(NSString *)peerID{

    a_home_dir = NSHomeDirectory();
    NSString* a_doc_dir = [a_home_dir stringByAppendingPathComponent:@"Documents"];
    a_path = [a_doc_dir stringByAppendingPathComponent:@"userdata.plist"];

    NSDictionary *plist2 = [NSDictionary dictionaryWithContentsOfFile:a_path];
    switchcheck =[plist2 objectForKey:@"switchcheck"];
    swithchcheckint = [switchcheck intValue];

    if(swithchcheckint==1)
    {
        message102 =@"111";
    }
    else if(swithchcheckint==0)
    {
        message102 =@"110";
    }
    //---convert an NSString object to NSData---
    NSData* data;
     [messageTextField setText:message102];
     data = [message102 dataUsingEncoding:NSUTF8StringEncoding];
    [self mySendDataToPeers:data:peerID];
}


@end

请有人帮忙。

4

1 回答 1

1

Apple 只允许应用程序的后台处理持续 10 分钟(过去只有 5 分钟),除非应用程序是音乐、VOIP 或导航,在这种情况下,您需要在 Plist 文件中指定。

这就是为什么您的应用程序在 10 分钟后停止的原因,默认情况下 Xcode 将在您调试时继续运行应用程序。

于 2012-09-25T12:26:15.363 回答