2017-07-25 93 views
4

我需要检查应用程序是否移动到了后台。为什么?Swift 3:检查应用程序是否在后台

那么因为我的应用程序使用蓝牙,一次只能有一个人连接到此设备。因此,如果他们没有使用它并且应用程序位于后台,请断开它们并将它们发送到连接主页面。

现在我已经完成了这个。我在主要的第一类中有一个选择器,并且具有断开连接并发送到第一页的功能。但是我没有意识到的是,如果控制面板被拖拽,应用程序将处于“背景”。

从环视看来,似乎没有办法检测控制面板是否长大。那么,有没有人有任何想法可以做到这一点?

实际上,我只是想要它,所以如果应用程序被移动到背景以外的任何其他原因比控制面板被提出,断开设备。

选择:

let notificationCenter = NotificationCenter.default 
notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: Notification.Name.UIApplicationWillResignActive, object: nil) 

功能:

@objc func appMovedToBackground() { 
     if (ViewController.connectedPeripheral != nil) { 
      print("App moved to background!") 
      let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil) 
      let nextViewController = storyBoard.instantiateViewController(withIdentifier: "connectView") as! ViewController 
      self.navigationController?.pushViewController(nextViewController, animated: true) 
      ViewController.centralManager.cancelPeripheralConnection(ViewController.connectedPeripheral!) 
     } 
     else { 
      print("App moved to background but no device is connected so no further action taken") 
     } 
    } 

这不是其他问题重复。我知道如何检查应用程序是否处于后台状态。我只是不想在控制面板被拔出时断开连接...

+1

UIApplicationDidEnterBackground通知是您要查找的内容吗? –

回答

1

您是否尝试将viewResver添加到您的视图控制器中的willResignActive中?

NotificationCenter.default.addObserver(self, selector: #selector(willResignActive), name: .UIApplicationWillResignActive, object: nil) 


func willResignActive(_ notification: Notification) { 
    // code to execute 
} 
0

然后你也可以使用它。进入后台状态后,应用程序将被移至非活动状态。

override func viewDidLoad() { 
    super.viewDidLoad() 

    let app = UIApplication.shared 

    //Register for the applicationWillResignActive anywhere in your app. 
    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.applicationWillResignActive(notification:)), name: NSNotification.Name.UIApplicationWillResignActive, object: app) 
} 

func applicationWillResignActive(notification: NSNotification) { 

} 
+0

欣赏评论。我已经有了这个。真正的问题是,我们如何能够检测到控制面板已经被提出......但我想这是没有办法的。 – jackabe

+0

不,没有其他方法可以检测应用程序移到背景的原因。 – 2017-07-25 13:13:02

1

在斯威夫特:

if UIApplication.shared.applicationState == .background { 
    // Add code here... 
} 

在Objective-C:

if ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground) { 
    // Add code here... 
} 

希望工程!

相关问题