如果你希望使用iPhone的網絡功能並保持長連接,並使用Wifi的話,你可能會發現一個問題,那就是在iPhone處於睡眠狀態時,Wifi會中斷,這樣程序就無法保持連接。(iPhone非官方SDK)
下面的代碼可能會幫你解決這個問題。
以下代碼摘自MobileChat:
首先在applicationDidFinishLaunching方法中添加以下代碼:
IONotificationPortRef notificationPort;
root_port = IORegisterForSystemPower(self, ¬ificationPort, powerCallback, ¬ifier);
CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(notificationPor t), kCFRunLoopCommonModes);
接著添加如下全局方法(在所有類之外添加)
void powerCallback(void *refCon, io_service_t service, natural_t messageType, void *messageArgument) {
[(YourAppnameApp*)refCon powerMessageReceived: messageType withArgument: messageArgument];
}
在你的程序裡添加下面的代碼:
- (void)powerMessageReceivednatural_t)messageType withArgumentvoid *) messageArgument {
switch (messageType) {
case kIOMessageSystemWillSleep:
IOAllowPowerChange(root_port, (long)messageArgument);
break;
case kIOMessageCanSystemSleep:
//if([self wifiKeepAliveIsSet]) {
IOCancelPowerChange(root_port, (long)messageArgument);
//}
break;
case kIOMessageSystemHasPoweredOn:
break;
}
}
這樣就可以保持iPhone在網絡連接的狀況下不睡眠了(當然,可能會比較費電 ^_^)。 |