1.在xxx-info.plist文件中, 新建一行 Required background modes , 加入下面两项。
App shares data using CoreBluetooth 和 App communicates using CoreBluetooth
当应用进入后台后, 蓝牙还是保持连接的, 也能够正常接收数据。但是来数据了, 如果要实时响应, 那就要用到本地推送了。
[(AppDelegate *)[[UIApplicationsharedApplication]delegate]receiveData];
receiveData写在Appdelegate.m中,这样当蓝牙设备发送消息给手机时,app若在后台运行,就可以在通知栏收到消息了,
我的代码:
//收到蓝牙设备返回内容
if([returnstr isEqualToString:@"a627f001"])
{
if([UIApplication sharedApplication].applicationState == UIApplicationStateActive)
{
[self playSound];
}
else
{
[(AppDelegate *)[[UIApplication sharedApplication] delegate] receiveData];
}
}
//APPdelegate注册本地通知
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if ([UIApplicationinstancesRespondToSelector:@selector(registerUserNotificationSettings:)])
{
[application registerUserNotificationSettings:[UIUserNotificationSettingssettingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSoundcategories:nil]];
}
}
//接受消息,通知栏响应
-(void)receiveData
{
NSLog(@"收到数据了");
//查找手表
UILocalNotification *Notification = [[UILocalNotificationalloc]init];
if (Notification)
{
Notification.timeZone = [NSTimeZonedefaultTimeZone];
Notification.repeatInterval =NSWeekCalendarUnit;
Notification.soundName = UILocalNotificationDefaultSoundName;
Notification.alertBody =@"查找手表";
Notification.alertAction =@"打开";
//显示在icon上的红色圈中的数子
Notification.applicationIconBadgeNumber =0;
//设置userinfo方便在之后需要撤销的时候使用
NSDictionary *infoDic = [NSDictionarydictionaryWithObject:@"name"forKey:@"key"];
noti.userInfo = infoDic;
//添加推送到uiapplication
UIApplication *app = [UIApplicationsharedApplication];
[app Notification];
}
}