简体   繁体   English

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

[英]run code on application launch OSX

I am looking for a way to have a certain bit of code run constantly as soon as the application starts up. 我正在寻找一种方法,以便在应用程序启动后立即不断运行某些代码。 I am trying to make a simple peer to peer chat application using swiftSockets . 我正在尝试使用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"
    }
}

I have the code above, the send works great, however, How can i get the receive function to run in the background as soon as the application is run? 我有上面的代码,发送效果很好,但是,如何在应用程序运行后立即让接收函数在后台运行?

Simply call your receive function in the viewDidLoad() or viewDidAppear() function. 只需在viewDidLoad()或viewDidAppear()函数中调用接收函数。 To have run it in the background, consider dispatch_async() or dispatch_sync() 要在后台运行它,请考虑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
    }
}

If you just want to run it periodically without the necessity of transferring it to the background, consider using an NSTimer, and call its scheduledTimerWithTimeInterval function similar to this: 如果您只想定期运行它,而不必将其传输到后台,请考虑使用NSTimer,然后调用类似于以下内容的ScheduledTimerWithTimeInterval函数:

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

with the first parameter being the interval in seconds, selector the function you want to periodically call (in this case receive). 第一个参数是以秒为单位的间隔,选择器要定期调用的函数(在这种情况下为接收)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM