iOS開發- 藍牙後臺接收數據(BLE4.0)

1.在xxx-info.plist文件中, 新建一行  Required background modes , 加入下面兩項。app

App shares data using CoreBluetooth 和 App communicates using CoreBluetooth
函數

如圖所示:ui



加入這個項後, 你會發現, 當應用進入後臺後, 藍牙仍是保持鏈接的。spa

可是, 進入後臺後, 雖然應用還掛着, 可以正常接收數據。可是,  來數據了, 若是須要咱們實時響應, 那就要用到推送了。.net

也就是, 當數據來的時候, 彈出一個提示框, 提示用戶來數據了。code


2. 設置本地推送orm

這裏的方法寫在AppDelegate.m中。  receiveData對應你接收到數據的響應函數。htm

[cpp] view plaincopy在CODE上查看代碼片派生到個人代碼片blog

  1. -(void)receiveData:(NSData*)data  ip

  2. {  

  3.     NSLog(@"收到數據了");  

  4.       

  5.     //收到數據, 設置推送  

  6.     UILocalNotification *noti = [[UILocalNotification alloc] init];  

  7.     if (noti)  

  8.     {  

  9.         //設置時區  

  10.         noti.timeZone = [NSTimeZone defaultTimeZone];  

  11.         //設置重複間隔  

  12.         noti.repeatInterval = NSWeekCalendarUnit;  

  13.         //推送聲音  

  14.         noti.soundName = UILocalNotificationDefaultSoundName;  

  15.         //內容  

  16.         noti.alertBody = @"接收到數據了";  

  17.         noti.alertAction = @"打開";  

  18.         //顯示在icon上的紅色圈中的數子  

  19.         noti.applicationIconBadgeNumber = 1;  

  20.         //設置userinfo 方便在以後須要撤銷的時候使用  

  21.         NSDictionary *infoDic = [NSDictionary dictionaryWithObject:@"name" forKey:@"key"];  

  22.         noti.userInfo = infoDic;  

  23.         //添加推送到uiapplication  

  24.         UIApplication *app = [UIApplication sharedApplication];  

  25.         [app scheduleLocalNotification:noti];  

  26.     }  

  27. }  


[cpp] view plaincopy在CODE上查看代碼片派生到個人代碼片

  1. #pragma mark - 接收到推送  

  2. - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification*)notification  

  3. {  

  4.     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"來電提示"  

  5.                                                     message:notification.alertBody  

  6.                                                    delegate:nil  

  7.                                           cancelButtonTitle:@"接聽"  

  8.                                           otherButtonTitles:@"掛斷",nil];  

  9.     [alert show];  

  10.     //這裏,你就能夠經過notification的useinfo,幹一些你想作的事情了  

  11.     application.applicationIconBadgeNumber -= 1;  

  12. }

相關文章
相關標籤/搜索