0
我正在尋找一種方法,讓應用程序啓動後不斷運行某些代碼。我正在嘗試使用swiftSockets來製作一個簡單的點對點聊天應用程序。在應用程序啓動時運行代碼OSX
import Cocoa
import CryptoSwift
class MasterViewController: NSViewController {
@IBOutlet var msgField: NSTextField!
@IBOutlet var msgWindow: NSTextView!
let server:UDPServer = UDPServer(addr: "127.0.0.1", port: 5000)
override func viewDidLoad() {
super.viewDidLoad()
}
func receive() {
let data = server.recv(1024)
let string = NSData.withBytes(data.0!)
let str = NSString(data: string, encoding: NSUTF8StringEncoding) as String?
msgWindow.string! += server.addr + " says: " + str! + "\n"
}
@IBAction func send(sender: NSButton) {
msgWindow.string! += "I said: " + msgField.stringValue + "\n"
msgField.stringValue = ""
server.send(str: msgField.stringValue)
let data = server.recv(1024)
let string = NSData.withBytes(data.0!)
let str = NSString(data: string, encoding: NSUTF8StringEncoding) as String?
msgWindow.string! += server.addr + " says: " + str! + "\n"
}
}
我上面的代碼,發送的偉大工程,但是,我怎麼能得到作爲運行應用程序的接收功能在後臺立即運行?
謝謝你,快問。我會在viewDidLoad()裏面運行dispatch_async()嗎? – bshah
是的,dispatch_async()將調度你想要的任務到後臺,所以最好在你的應用啓動的第一階段進行調度,viewDidLoad()就是一個很好的例子。 –