iPhone网络软件在睡眠情况断线 已解决

来源:互联网 发布:ipa应用分发源码 编辑:程序博客网 时间:2024/04/28 06:57

转自:http://mobile.51cto.com/iphone-277374.htm


iPhone网络软件在睡眠情况断线是本文要介绍的内容,如果你希望使用iPhone网络功能并保持长连接,并使用Wifi的话,你可能会发现一个问题,那就是在iPhone处于睡眠状态时,Wifi会中断,这样程序就无法保持连接。(iPhone非官方SDK)

下面的代码可能会帮你解决这个问题。

以下代码摘自MobileChat:

首先在applicationDidFinishLaunching方法中添加以下代码:

  1.  IONotificationPortRef notificationPort;  
  2. root_port = IORegisterForSystemPower(self, &notificationPort, powerCallback, &notifier);  
  3. CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(notificationPor t), kCFRunLoopCommonModes);  

接着添加如下全局方法(在所有类之外添加)

  1. void powerCallback(void *refCon, io_service_t service, natural_t messageType, void *messageArgument) {  
  2.  [(YourAppnameApp*)refCon powerMessageReceived: messageType withArgument: messageArgument];  

在你的程序里添加下面的代码:

  1. - (void)powerMessageReceived:(natural_t)messageType withArgument:(void *) messageArgument {  
  2.  switch (messageType) {  
  3.   case kIOMessageSystemWillSleep:  
  4.    IOAllowPowerChange(root_port, (long)messageArgument);   
  5.    break;  
  6.   case kIOMessageCanSystemSleep:  
  7.    //if([self wifiKeepAliveIsSet]) {  
  8.    IOCancelPowerChange(root_port, (long)messageArgument);  
  9.    //}  
  10.    break;   
  11.   case kIOMessageSystemHasPoweredOn:  
  12.    break;  
  13.  }  

这样就可以保持iPhone网络连接的状况下不睡眠了(当然,可能会比较费电 ^_^)。


原创粉丝点击