多重连接的广告商帮助快速4

时间:2018-05-30 23:38:07

标签: ios swift swift4 multipeer-connectivity

所以,我一直在寻找一个新的教程试图制作一个新的应用程序,但我很难更改打开连接页面的按钮。它现在的方式非常无关紧要。它提供了加入会话或主持会话的选项。我想制作一个按钮,当点击时只需要搜索其他设备而不是现在的功能。像我在链接底部发布的链接。我是swift和编码的初学者,所以如果这是一个愚蠢的问题,我很抱歉。我已经待了一个多月,没有运气。源代码在底部。任何帮助都会很棒。源代码甚至更好。我还“***”我认为是问题的代码块。但我不确定。提前致谢。

https://cdn-images-1.medium.com/max/1600/1*o3prbMNTHO8ZBz3oQejCOA.png

 import UIKit
 import MultipeerConnectivity

 class TodoTableViewController: UITableViewController, TodoCellDelegate, 
 MCSessionDelegate, MCBrowserViewControllerDelegate {


var todoItems:[TodoItem]!


var peerID:MCPeerID!
var mcSession:MCSession!
var mcAdvertiserAssistant:MCAdvertiserAssistant!


override func viewDidLoad() {
    super.viewDidLoad()

    loadData()

    peerID = MCPeerID(displayName: UIDevice.current.name)
    mcSession = MCSession(peer: peerID, securityIdentity: nil, encryptionPreference: .required)
    mcSession.delegate = self

}

func loadData(){
    todoItems = [TodoItem]()
    todoItems = DataManager.loadAll(TodoItem.self).sorted(by: {$0.createdAt < $1.createdAt})
    self.tableView.reloadData()
}



@IBAction func addTodo(_ sender: Any) {
    let addAlert = UIAlertController(title: "New Todo", message: "Enter a title", preferredStyle: .alert)
    addAlert.addTextField { (textfield:UITextField) in
        textfield.placeholder = "ToDo Item Title"
    }

    addAlert.addAction(UIAlertAction(title: "Create", style: .default, handler: { (action:UIAlertAction) in
        guard let title = addAlert.textFields?.first?.text else {return}
        let newTodo = TodoItem(title: title, completed: false, createdAt: Date(), itemIdentifier: UUID())
        newTodo.saveItem()
        self.todoItems.append(newTodo)

        let indexPath = IndexPath(row: self.tableView.numberOfRows(inSection: 0), section: 0)

        self.tableView.insertRows(at: [indexPath], with: .automatic)
    }))

    addAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

    self.present(addAlert, animated: true, completion: nil)

}


// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {

    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return todoItems.count
}


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TodoTableViewCell

    let todoItem = todoItems[indexPath.row]
    cell.todoLabel.text = todoItem.title
    cell.delegte = self

    if todoItem.completed {
        cell.todoLabel.attributedText = strikeThroughText(todoItem.title)
    }

    return cell
}

func didRequestDelete(_ cell: TodoTableViewCell) {

    if let indexPath = tableView.indexPath(for: cell) {
        todoItems[indexPath.row].deleteItem()
        todoItems.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: .automatic)

    }
}

func didRequestComplete(_ cell: TodoTableViewCell) {

    if let indexPath = tableView.indexPath(for: cell) {
        var todoItem = todoItems[indexPath.row]
        todoItem.markAsCompleted()
        cell.todoLabel.attributedText = strikeThroughText(todoItem.title)
    }
}

func didRequestShare(_ cell: TodoTableViewCell) {
    if let indexPath = tableView.indexPath(for: cell) {
        let todoItem = todoItems[indexPath.row]
        sendTodo(todoItem)
    }
}

func sendTodo (_ todoItem:TodoItem) {
    if mcSession.connectedPeers.count > 0 {
        if let todoData = DataManager.loadData(todoItem.itemIdentifier.uuidString) {
            do {
                try mcSession.send(todoData, toPeers: mcSession.connectedPeers, with: .reliable)
            }catch{
                fatalError("Could not send todo item")
            }
        }
    }else{
        print("you are not connected to another device")
    }
}


func strikeThroughText (_ text:String) -> NSAttributedString {
    let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: text)
    attributeString.addAttribute(NSAttributedStringKey.strikethroughStyle, value: 1, range: NSMakeRange(0, attributeString.length))

    return attributeString
}


// MARK: - Multipeer Connectivity


***@IBAction func showConnectivityActions(_ sender: Any) {
    let actionSheet = UIAlertController(title: "ToDo Exchange", message: "Do you want to Host or Join a session?", preferredStyle: .actionSheet)

    actionSheet.addAction(UIAlertAction(title: "Host Session", style: .default, handler: { (action:UIAlertAction) in

        self.mcAdvertiserAssistant = MCAdvertiserAssistant(serviceType: "ba-td", discoveryInfo: nil, session: self.mcSession)
        self.mcAdvertiserAssistant.start()

    }))

    actionSheet.addAction(UIAlertAction(title: "Join Session", style: .default, handler: { (action:UIAlertAction) in
        let mcBrowser = MCBrowserViewController(serviceType: "ba-td", session: self.mcSession)
        mcBrowser.delegate = self
        self.present(mcBrowser, animated: true, completion: nil)
    }))

    actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

    self.present(actionSheet, animated: true, completion: nil)

}***

func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) {
    switch state {
    case MCSessionState.connected:
        print("Connected: \(peerID.displayName)")

    case MCSessionState.connecting:
        print("Connecting: \(peerID.displayName)")

    case MCSessionState.notConnected:
        print("Not Connected: \(peerID.displayName)")
    }
}

func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) {

    do {
        let todoItem = try JSONDecoder().decode(TodoItem.self, from: data)

        DataManager.save(todoItem, with: todoItem.itemIdentifier.uuidString)

        DispatchQueue.main.async {
            self.todoItems.append(todoItem)

            let indexPath = IndexPath(row: self.tableView.numberOfRows(inSection: 0), section: 0)

            self.tableView.insertRows(at: [indexPath], with: .automatic)
        }

    }catch{
        fatalError("Unable to process recieved data")
    }

}

func session(_ session: MCSession, didReceive stream: InputStream, withName streamName: String, fromPeer peerID: MCPeerID) {

}

func session(_ session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, with progress: Progress) {

}

func session(_ session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, at localURL: URL?, withError error: Error?) {

}


func browserViewControllerDidFinish(_ browserViewController: MCBrowserViewController) {
    dismiss(animated: true, completion: nil)
}

func browserViewControllerWasCancelled(_ browserViewController: MCBrowserViewController) {
    dismiss(animated: true, completion: nil)
}

0 个答案:

没有答案