iOS開發- 藍芽後台接收資料(BLE4.0)

來源:互聯網
上載者:User

標籤:

最近在做一個藍芽相關的項目, 需要在應用進入後台, 或者手機屬於鎖屏狀態的情況下, 仍然保持藍芽串連, 並且能正常接收資料。

本來以後會很麻煩, 但是學習了下..發現就2步而已。簡單的不能再簡單了。

 

好了。下面是具體實現辦法。

 

1.在xxx-info.plist檔案中, 建立一行  Required background modes
 , 加入下面兩項。

App shares data using CoreBluetooth
 和  App communicates using CoreBluetooth

:

 

加入這個項後, 你會發現, 當應用進入後台後, 藍芽還是保持串連的。

但是, 進入後台後, 雖然應用還掛著, 能夠正常接收資料。但是,  來資料了, 如果需要我們即時響應, 那就要用到推送了。

也就是, 當資料來的時候, 彈出一個提示框, 提示使用者來資料了。

 

2. 設定本地推送

這裡的方法寫在AppDelegate.m中。  receiveData對應你接收到資料的響應函數。

-(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 = @"開啟";          //顯示在icon上的紅色圈中的數子          noti.applicationIconBadgeNumber = 1;          //設定userinfo 方便在之後需要撤銷的時候使用          NSDictionary *infoDic = [NSDictionary dictionaryWithObject:@"name" forKey:@"key"];          noti.userInfo = infoDic;          //添加推送到uiapplication          UIApplication *app = [UIApplication sharedApplication];          [app scheduleLocalNotification:noti];      }  }  
#pragma mark - 接收到推送  - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification*)notification  {      UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"來電提示"                                                      message:notification.alertBody                                                     delegate:nil                                            cancelButtonTitle:@"接聽"                                            otherButtonTitles:@"掛斷",nil];      [alert show];      //這裡,你就可以通過notification的useinfo,幹一些你想做的事情了      application.applicationIconBadgeNumber -= 1;  }  

 

iOS開發- 藍芽後台接收資料(BLE4.0)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.