2015-11-19 73 views
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" 
    } 
} 

我上面的代碼,發送的偉大工程,但是,我怎麼能得到作爲運行應用程序的接收功能在後臺立即運行?

回答

0

只需在viewDidLoad()或viewDidAppear()函數中調用您的接收函數即可。要在後臺已運行它,考慮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) 

與所述第一參數是在幾秒鐘的時間間隔,選擇器要定期調用(在這種情況下接收)的功能。

+0

謝謝你,快問。我會在viewDidLoad()裏面運行dispatch_async()嗎? – bshah

+0

是的,dispatch_async()將調度你想要的任務到後臺,所以最好在你的應用啓動的第一階段進行調度,viewDidLoad()就是一個很好的例子。 –

相關問題