2015-05-06 47 views
1

在詢問之前,我已經閱讀了幾個問題/答案,並且還附加了過程,但似乎不起作用。父handleLatchKitExtensionRequest從未被調用?

我的watchkit擴展是用Swift編寫的,而AppDelegate是Objective-C(因爲它是舊代碼)。

在我的分機,我叫:

@IBAction func toPage2() { 
    println("to page 2") 
    WKInterfaceController.openParentApplication(["page":"2"], reply: {(reply, error) -> Void in }) 
} 

在我的AppDelegate,我試着打印

- (void)application:(UIApplication *)application handleWatchKitExtensionRequest:(NSDictionary *)userInfo reply:(void(^)(NSDictionary *replyInfo))reply 
{ 
NSLog(@"handle watchkit"); 

NSString *file = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"page2"] ofType:@"wav"]; 
AVAudioPlayer *audio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:file] error:nil]; 
[audio play]; 
... 

我也嘗試調試>附加到進程,然後選擇iPhone應用程序,並且仍然一無所獲發生了。任何人都可以指出我的方向嗎?

+0

是否也發生在當主的iPhone應用程序是活動的模擬器這個問題?也許這有助於:http://stackoverflow.com/questions/30000274/calling-parent-application-from-watch-app – vomako

回答

0

您需要註冊後臺模式音頻,然後把你的代碼和一個UIBackgroundTask包裹它也需要返回reply()爲您handleWatchKitExtensionRequest

這部分是background tasks

+1

你不需要註冊一個背景模式。如果您沒有播放背景音頻,這會導致您的應用被拒絕。 – bgilham

+0

您正在使用'handleWatchKitExtensionRequest',如果它未在前臺運行,它將啓動您的應用到後臺。 – rmp

+0

我在前臺運行應用程序...沒有打印出來,沒有播放。 –

1
一個很好的鏈接

documentation中指定的handleWatchKitExtensionRequest中啓動後臺任務。這可確保iPhone上的主應用程序在發送其答覆之前不會暫停(當iPhone上的應用程序未處於活動狀態時)。

代碼在主應用程序的iPhone上的應用程序的委託:

- (void)application:(UIApplication *)application handleWatchKitExtensionRequest:(NSDictionary *)userInfo reply:(void (^)(NSDictionary *))reply 
{ 
    __block UIBackgroundTaskIdentifier watchKitHandler; 
    watchKitHandler = [[UIApplication sharedApplication] beginBackgroundTaskWithName:@"backgroundTask" 
                   expirationHandler:^{ 
                   watchKitHandler = UIBackgroundTaskInvalid; 
                   }]; 

    if ([[userInfo objectForKey:@"request"] isEqualToString:@"getData"]) 
    { 
     // get data 
     // ... 
     reply(data); 
    } 

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)NSEC_PER_SEC * 1), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
     [[UIApplication sharedApplication] endBackgroundTask:watchKitHandler]; 
    }); 
}