生活随笔
收集整理的這篇文章主要介紹了
iOS开发- 蓝牙后台接收数据(BLE4.0)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
最近在做一個藍牙相關的項目, 需要在應用進入后臺, 或者手機屬于鎖屏狀態的情況下, 仍然保持藍牙連接, 并且能正常接收數據。
本來以后會很麻煩, 但是學習了下..發現就2步而已。簡單的不能再簡單了。
好了。下面是具體實現辦法。
1.在xxx-info.plist文件中, 新建一行 ?Required background modes?, 加入下面兩項。
App shares data using CoreBluetooth?和?App communicates using CoreBluetooth
如圖所示:
加入這個項后, 你會發現, 當應用進入后臺后, 藍牙還是保持連接的。
但是, 進入后臺后, 雖然應用還掛著, 能夠正常接收數據。但是, ?來數據了, 如果需要我們實時響應, 那就要用到推送了。
也就是, 當數據來的時候, 彈出一個提示框, 提示用戶來數據了。
2. 設置本地推送
這里的方法寫在AppDelegate.m中。 ?receiveData對應你接收到數據的響應函數。
[cpp]?view plaincopy
-(void)receiveData:(NSData*)data?? {?? ????NSLog(@"收到數據了");?? ?????? ?????? ????UILocalNotification?*noti?=?[[UILocalNotification?alloc]?init];?? ????if?(noti)?? ????{?? ?????????? ????????noti.timeZone?=?[NSTimeZone?defaultTimeZone];?? ?????????? ????????noti.repeatInterval?=?NSWeekCalendarUnit;?? ?????????? ????????noti.soundName?=?UILocalNotificationDefaultSoundName;?? ?????????? ????????noti.alertBody?=?@"接收到數據了";?? ????????noti.alertAction?=?@"打開";?? ?????????? ????????noti.applicationIconBadgeNumber?=?1;?? ?????????? ????????NSDictionary?*infoDic?=?[NSDictionary?dictionaryWithObject:@"name"?forKey:@"key"];?? ????????noti.userInfo?=?infoDic;?? ?????????? ????????UIApplication?*app?=?[UIApplication?sharedApplication];?? ????????[app?scheduleLocalNotification:noti];?? ????}?? }?? [cpp]?view plaincopy
#pragma?mark?-?接收到推送??-?(void)application:(UIApplication?*)application?didReceiveLocalNotification:(UILocalNotification*)notification??{??????UIAlertView?*alert?=?[[UIAlertView?alloc]?initWithTitle:@"來電提示"??????????????????????????????????????????????????????message:notification.alertBody?????????????????????????????????????????????????????delegate:nil????????????????????????????????????????????cancelButtonTitle:@"接聽"????????????????????????????????????????????otherButtonTitles:@"掛斷",nil];??????[alert?show];????????????application.applicationIconBadgeNumber?-=?1;??}?
轉載于:https://www.cnblogs.com/AlvinCrash/p/5379458.html
總結
以上是生活随笔為你收集整理的iOS开发- 蓝牙后台接收数据(BLE4.0)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。