简体   繁体   English

BLE iOS9的Swift背景模式

[英]Swift background mode for BLE iOS9

I want to improve the MPCRevisited project which is Chat app that using multi peer method. 我想改进MPCRevisited项目,即使用多同伴方法的聊天应用程序。 I'm using BLE to connect one device to another device (iPad and iPod) and send and receive the data. 我正在使用BLE将一台设备连接到另一台设备(iPad和iPod)并发送和接收数据。 However, when I press home button to make background mode on one device, after 5 seconds, I can't send or receive the data. 但是,当我按下主页按钮在一台设备上进行后台模式时,5秒后,我无法发送或接收数据。

image description here 图像描述在这里

在此输入图像描述

I've already check all the thing in background modes, but still its not working at all. 我已经在后台模式中检查了所有内容,但它仍然无法正常工作。

import UIKit
import MultipeerConnectivity

class ParkBenchTimer {

    let startTime:CFAbsoluteTime
    var endTime:CFAbsoluteTime?

    init() {
        startTime = CFAbsoluteTimeGetCurrent()
    }

    func stop() -> CFAbsoluteTime {
        endTime = CFAbsoluteTimeGetCurrent()

        return duration!
    }

    var duration:CFAbsoluteTime? {
        if let endTime = endTime {
            return endTime - startTime
        } else {
            return nil
        }
    }
}



class ChatViewController: UIViewController, UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var chatTextField: UITextField!

    @IBOutlet weak var chatTableView: UITableView!

    var messagesArray: [[String : String]] = []

    let mpcManager = MPCManager.sharedInstance


    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        self.chatTableView.delegate = self
        self.chatTableView.dataSource = self

        self.chatTableView.estimatedRowHeight = 60.0
        self.chatTableView.rowHeight = UITableViewAutomaticDimension

        self.chatTextField.delegate = self

        self.mpcManager.messageRecievedDelegate = self
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */


    // MARK: IBAction method implementation

    @IBAction func endChat(sender: AnyObject) {
        let messageDictionary: [String: String] = ["message": "_end_chat_"]
        if self.mpcManager.sendData(dictionaryWithData: messageDictionary, toPeer: self.mpcManager.session.connectedPeers[0] as MCPeerID){
            self.dismissViewControllerAnimated(true, completion: { () -> Void in
                self.mpcManager.session.disconnect()
            })
        }
    }


    // MARK: UITableView related method implementation

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }


    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.messagesArray.count
    }


    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        guard let cell = tableView.dequeueReusableCellWithIdentifier("idCell") else {
            assert(true)
            return UITableViewCell()
        }

        guard let currentMessage = self.messagesArray[safe: indexPath.row] else {
            print(" ")
            assert(true)
            return UITableViewCell()
        }

        if let sender = currentMessage["sender"] {
            var senderLabelText: String
            var senderColor: UIColor

            if sender == "self" {

                senderLabelText = "I said:"
                senderColor = UIColor.purpleColor()

            } else {

                senderLabelText = sender + " said:"
                senderColor = UIColor.orangeColor()

            }

            cell.detailTextLabel?.text = senderLabelText
            cell.detailTextLabel?.textColor = senderColor
        }

        if let message = currentMessage["message"] {
            cell.textLabel?.text = message
        }

        return cell
    }



    // MARK: UITextFieldDelegate method implementation

    func textFieldShouldReturn(textField: UITextField) -> Bool {
        textField.resignFirstResponder()

        guard let textFieldText = textField.text else {
            assert(true)
            return false
        }


        let messageDictionary: [String: String] = ["message": textFieldText]

        guard let connectedPeer = self.mpcManager.session.connectedPeers[safe: 0] else {

            print(" ")
            assert(true)
            return false
        }

        if self.mpcManager.sendData(dictionaryWithData: messageDictionary, toPeer: connectedPeer) {

            let dictionary = ["sender": "self", "message": textFieldText]
            self.messagesArray.append(dictionary)

            self.updateTableview()

        } else {

            print("Could not send data")

        }

        textField.text = ""

        return true
    }


    // MARK: Custom method implementation

    func updateTableview(){
        chatTableView.reloadData()

        if self.chatTableView.contentSize.height > self.chatTableView.frame.size.height {

            let indexPathToScrollTo = NSIndexPath(forRow: messagesArray.count - 1, inSection: 0)

            self.chatTableView.scrollToRowAtIndexPath(indexPathToScrollTo, atScrollPosition: .Bottom, animated: true)
        }
    }


}

extension ChatViewController : MPCManagerRecievedMessageDelegate {
    func managerRecievedData(data:NSData ,fromPeer:MCPeerID) {
        // Convert the data (NSData) into a Dictionary object.
        let dataDictionary = NSKeyedUnarchiver.unarchiveObjectWithData(data) as! [String : String]


        // Check if there's an entry with the "message" key.
        if let message = dataDictionary["message"] {
            // Make sure that the message is other than "_end_chat_".
            if message != "_end_chat_"{

                // Create a new dictionary and set the sender and the received message to it.
                let messageDictionary: [String: String] = ["sender": fromPeer.displayName, "message": message]

                // Add this dictionary to the messagesArray array.
                messagesArray.append(messageDictionary)

                // Reload the tableview data and scroll to the bottom using the main thread.
                self.updateTableview()

            } else {


            }
        }

    }

    func managerDidRecievedMessage(message: String, fromPeer: MCPeerID) {
        // Create a new dictionary and set the sender and the received message to it.
        //let messageDictionary: [String: String] = ["sender": fromPeer.displayName, "message": message]

        // Add this dictionary to the messagesArray array.
        //messagesArray.append(messageDictionary)

        // Reload the tableview data and scroll to the bottom using the main thread.
        //self.updateTableview()
    }

    func managerDidEndChat(fromPeer:MCPeerID) {

        // In this case an "_end_chat_" message was received.
        // Show an alert view to the user.
        let alert = UIAlertController(title: "", message: "\(fromPeer.displayName) ended this chat.", preferredStyle: UIAlertControllerStyle.Alert)

        let doneAction: UIAlertAction = UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default) { (alertAction) -> Void in
            self.mpcManager.session.disconnect()
            self.dismissViewControllerAnimated(true, completion: nil)
        }

        alert.addAction(doneAction)

        self.presentViewController(alert, animated: true, completion: nil)

    }
}

This is my code. 这是我的代码。

Please help me if someone knows this problem. 如果有人知道这个问题,请帮助我。 What I want to do is one device to keep sending the message and other device to become background and foreground back and forth. 我想要做的是一个设备继续发送消息和其他设备来回成为背景和前景。

Thank you. 谢谢。

Looking at some other StackOverflow posts ( here and here ), it seems like the Multipeer Connectivity Framework is not built to function in the background and your functionality will disappear after a couple minutes. 看看其他一些StackOverflow帖子( 此处此处 ),似乎Multipeer Connectivity Framework不能在后台运行,几分钟后您的功能就会消失。

Bluetooth will function in the background, with the capabilities that you checked, but you will have to create your own messaging platform; 蓝牙在后台运行,具有您检查的功能,但您必须创建自己的消息传递平台; even though Multipeer relies partially on Bluetooth, the capabilities are separate entities. 尽管Multipeer部分依赖蓝牙,但功能却是独立的实体。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM