本地 Mac 上两个 macOS 应用之间的互联互通可以使用 Apple 的基于通知中心的互联互通机制来实现。以下是一个示例代码,演示了如何在两个应用之间发送和接收消息。
发送方应用代码示例(发送消息):
import Foundation
import NotificationCenter
// 消息发送方应用
class SenderApp {
let notificationCenter = DistributedNotificationCenter.default()
let notificationName = Notification.Name("com.example.notification")
func sendMessage() {
let message = "Hello, ReceiverApp!"
notificationCenter.post(name: notificationName, object: nil, userInfo: ["message": message])
}
}
let senderApp = SenderApp()
senderApp.sendMessage()
接收方应用代码示例(接收消息):
import Foundation
import NotificationCenter
// 消息接收方应用
class ReceiverApp {
let notificationCenter = DistributedNotificationCenter.default()
let notificationName = Notification.Name("com.example.notification")
func startListening() {
notificationCenter.addObserver(self, selector: #selector(receiveMessage(notification:)), name: notificationName, object: nil)
}
@objc func receiveMessage(notification: NSNotification) {
if let message = notification.userInfo?["message"] as? String {
print("Received message: \(message)")
}
}
}
let receiverApp = ReceiverApp()
receiverApp.startListening()
以上代码示例中,发送方应用通过 DistributedNotificationCenter 发送一个名为 "com.example.notification" 的通知,接收方应用通过该通知的名称注册成为观察者,并实现 receiveMessage 方法来接收消息。
请注意,为了使这个示例代码能够正常工作,需要在两个应用的 Info.plist 文件中添加以下配置:
发送方应用的 Info.plist 文件中添加:
NSDistributedNotificationsUsageDescription
需要发送消息给接收方应用。
接收方应用的 Info.plist 文件中添加:
NSDistributedNotificationsUsageDescription
需要接收发送方应用的消息。
这些配置是必需的,以确保应用程序可以相互通信。