class ViewController: UIViewController, NSMachPortDelegate {
let mainPort = Port()
override func viewDidLoad() {
super.viewDidLoad()
testPost()
}
func testPost() {
mainPort.setDelegate(self)
RunLoop.current.add(mainPort, forMode: .default)
Thread.detachNewThreadSelector(.threadCallBack, toTarget: objc, with: mainPort)
let btn = UIButton(frame: CGRect(x: 80, y: 200, width: 90, height: 40))
btn.setTitle("发送", for: .normal)
btn.setTitleColor(.cyan, for: .normal)
btn.addTarget(self, action: #selector(sendAsync), for: .touchUpInside)
view.addSubview(btn)
}
@objc func sendAsync() {
objc.minePort.send(before: Date(timeIntervalSince1970: Date().timeIntervalSince1970 + 2), components: NSMutableArray(array: ["post".data(using: .utf8)!]), from: mainPort, reserved: 0)
}
}
class LoginTool : NSObject, NSMachPortDelegate {
var minePort = Port()
var otherPort: Port?
@objc func callBack(mainPort: Port) {
otherPort = mainPort
minePort.setDelegate(self)
RunLoop.current.add(minePort, forMode: .default)
RunLoop.current.run()
}
func sendMesage() {
let str = "fa"
let str1 = "fa"
otherPort!.send(before: Date(timeIntervalSince1970: Date().timeIntervalSince1970 + 2), components: NSMutableArray(array: [str.data(using: .utf8)!,str1.data(using: .utf8)!]), from: minePort, reserved: 0)
}
func handleMachMessage(_ msg: UnsafeMutableRawPointer) {
print("收到了主线程的消息")
}
}
fileprivate extension Selector {
static let threadCallBack = #selector(LoginTool.callBack(mainPort:))
}