簡體   English   中英

快速插座連接

[英]Socket connection in swift

我正在用swift學習和開發ios應用程序。我的應用程序中有2個選項卡,所以我有2個視圖控制器。我需要連接套接字服務器。但是在哪個文件中?

第一個選項卡顯示對話列表,第二個選項卡是聊天界面。用戶正在從第二個選項卡發送消息。如果有人向該用戶發送消息,我需要在第一個選項卡中顯示此消息。

我需要連接套接字服務器,但是在哪個文件中? 我的意思是示例:當消息到達此用戶時,我需要將其保存到數據庫並在第二個選項卡中顯示用戶。視圖控制器文件是否適合這種情況?

我建議您檢查Alamofire 這是一個完全為Swift構建的出色的網絡庫,並且在過去的幾個月中確實得到了普及。 這使得調用Web服務來獲取數據變得異常容易。

Web套接字

如果您實際上需要使用Web套接字連接到服務器,則可以查看Square的優秀人員構建的SocketRocket 這是他們在Github上的項目的鏈接。

由於您是iOS開發的新手,因此建議您使用一種簡單的體系結構,在該體系結構中從視圖控制器中提取網絡調用。

聊天管理器

  • 內部管理所有網絡,例如SocketRocket
  • 應該是UIApplicationDelegate上的單例或屬性
  • 具有用於發送消息的公共API
  • 收到通知后發送通知

class ChatManager {

    // Add property for socket

    class var sharedInstance: ChatManager {
        struct Singleton { static let instance = ChatManager() }
        return Singleton.instance
    }

    init() {
        // Create the socket
    }

    func sendMessage(message: String) {
        // Push the message onto the socket
    }

    // Delegate methods

    func messageReceived(message: String) {
        // Emit the message using NSNotificationCenter
    }
}

視圖控制器1

  • 訂閱來自ChatManager的通知

class ViewController1 : UIViewController {
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)

        // Register for NSNotification coming from ChatManager
    }

    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)

        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}

視圖控制器2

  • 訂閱來自ChatManager的通知
  • 向ChatManager發送新消息以推送套接字

class ViewController2 : UIViewController {
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)

        // Register for NSNotification coming from ChatManager
    }

    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)

        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

    func userAddedNewChatMessage(message: String) {
        ChatManager.sharedInstance.sendMessage(message)
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM