在应用程序启动OSX上运行代码

时间:2015-11-19 02:39:42

标签: xcode swift macos cocoa

我正在寻找一种方法,可以在应用程序启动后立即运行一定数量的代码。我正在尝试使用swiftSockets创建一个简单的点对点聊天应用程序。

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"
    }
}

我有上面的代码,发送效果很好,但是,如何在应用程序运行后立即让接收函数在后台运行?

1 个答案:

答案 0 :(得分:0)

只需在viewDidLoad()或viewDidAppear()函数中调用receive函数即可。要在后台运行它,请考虑dispatch_async()或dispatch_sync()

let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0)) {
    // do some tasks, in this case call receive()
    dispatch_async(dispatch_get_main_queue()) {
        // update some UI
    }
}

如果您只想定期运行它而无需将其转移到后台,请考虑使用NSTimer,并调用其scheduledTimerWithTimeInterval函数,类似于:

let timer = NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: "receive", userInfo: nil, repeats: true)

第一个参数是以秒为单位的间隔,选择你想要定期调用的函数(在这种情况下是接收)。