gpt4 book ai didi

ios - swift 套接字连接

转载 作者:行者123 更新时间:2023-11-28 09:38:20 27 4
gpt4 key购买 nike

我正在使用 swift 学习和开发 ios 应用程序。我的应用程序中有 2 个选项卡,所以我有 2 个 View Controller 。我需要连接套接字服务器。但是在哪个文件中?

第一个选项卡显示对话列表,第二个选项卡是聊天界面。用户正在从第二个选项卡发送消息。如果有人向该用户发送消息,我需要在第一个选项卡中显示此消息。

我需要连接套接字服务器,但在哪个文件中?我的意思是示例:当消息到达该用户时,我需要将其保存到数据库并在第二个选项卡中显示用户。 View Controller 文件适合这种情况吗?

最佳答案

我建议查看 Alamofire .这是一个完全为 Swift 构建的很棒的网络库,并且在过去几个月中真正流行起来。这使得调用 Web 服务来获取数据变得异常容易。

WebSockets

如果您确实需要使用网络套接字连接到您的服务器,那么我会查看 SocketRocket由 Square 的优秀人士 build 。这是他们在 Github 上的项目的链接.

由于您是 iOS 开发的新手,我建议您使用一个简单的架构,在该架构中,您可以从 View Controller 中抽象出网络调用。

聊天管理器

  • 在内部管理所有网络,例如 SocketRocket
  • 应该是 UIApplicationDelegate 上的单例或属性
  • 具有用于发送消息的公共(public) 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
}
}

查看 Controller 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)
}
}

View Controller 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)
}
}

关于ios - swift 套接字连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29000416/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com