Swift2 我们如何在没有任何用户输入的情况下从文本文件或服务器连续读取数据

Swift2 我们如何在没有任何用户输入的情况下从文本文件或服务器连续读取数据,swift2,Swift2,我创建了一个变量“a”,例如,它的值来自我桌面上的文本文件。我希望连续读取数据并在应用程序中显示“a”的值 即使我更改了文本文件中的值,它也会自动反映在我的应用程序中 有什么建议吗 我正在使用Swift 2.2,您可以使用GCD的Dispatch Source监视文件。下面是一个简单的例子,我们监视一个文件,并在每次更新后用文件的内容更新NSTextView class ViewController: NSViewController { @IBOutlet var textView:

我创建了一个变量“a”,例如,它的值来自我桌面上的文本文件。我希望连续读取数据并在应用程序中显示“a”的值

即使我更改了文本文件中的值,它也会自动反映在我的应用程序中

有什么建议吗


我正在使用Swift 2.2,您可以使用GCD的Dispatch Source监视文件。下面是一个简单的例子,我们监视一个文件,并在每次更新后用文件的内容更新
NSTextView

class ViewController: NSViewController {
    @IBOutlet var textView: NSTextView!

    // Create a dispatch_source_t to monitor the file
    func dispatchSoureForFile(at path: String) -> dispatch_source_t? {
        let fileHandle = open(path.cStringUsingEncoding(NSUTF8StringEncoding)!, O_RDONLY)

        // Cannot open file
        guard fileHandle != -1 else {
            return nil
        }

        // The queue where the event handler will execute. Don't set to the main queue
        let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)

        // The events we are interested in
        let mask = DISPATCH_VNODE_DELETE | DISPATCH_VNODE_WRITE | DISPATCH_VNODE_EXTEND

        return dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE, UInt(fileHandle), mask, queue)
    }

    // The function to use for monitoring a file
    func startMonitoringFile(at path: String) {
        guard let dispatchSource = dispatchSoureForFile(at: path) else {
            print("Cannot create dispatch source to monitor file at '\(path)'")
            return
        }

        let eventHandler = {
            let data = dispatch_source_get_data(dispatchSource)

            // Tell what change happened to the file. Delete it if you want
            if data & DISPATCH_VNODE_WRITE != 0 {
                print("File is written to")
            }
            if data & DISPATCH_VNODE_EXTEND != 0 {
                print("File is extended to")
            }
            if data & DISPATCH_VNODE_DELETE != 0 {
                print("File is deleted")
            }

            // Sometimes the old version of the file is deleted before the new version is written
            // to disk. This happens when you call `writeToFile(_, atomically: true)` for example.
            // In that case, we want to stop monitoring at the old node and start at the new node
            if data & DISPATCH_VNODE_DELETE == 1 {
                dispatch_source_cancel(dispatchSource)
                self.startMonitoringFile(at: path)
                return
            }

            // Always update the GUI from the main queue
            let fileContent = try! String(contentsOfFile: path)
            dispatch_async(dispatch_get_main_queue()) {
                self.textView.string = fileContent
            }
        }

        // When we stop monitoring a vnode, close the file handle
        let cancelHandler = {
            let fileHandle = dispatch_source_get_handle(dispatchSource)
            close(Int32(fileHandle))
        }

        dispatch_source_set_registration_handler(dispatchSource, eventHandler)
        dispatch_source_set_event_handler(dispatchSource, eventHandler)
        dispatch_source_set_cancel_handler(dispatchSource, cancelHandler)
        dispatch_resume(dispatchSource)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.startMonitoringFile(at: "/path/to/file.txt")
    }
}
要触发
DISPATCH\u VNODE\u EXTEND
事件,您可以在终端上尝试以下操作:

echo "Hello world" >> /path/to/file.txt

我为一个非常类似的用例成功地使用了以下代码(在Swift 3.x中)。希望能有帮助

override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addObserver(
        self,
        selector: #selector(ViewController.commandOutputNotification(_:)),
        name: NSNotification.Name.NSFileHandleDataAvailable,
        object: nil)

    self.startTasks()
}

func startTasks() {
    self.task = Process()
    self.task!.terminationHandler = self.commandTerminationHandler
    let argumentsString = "tail -n 1 -f /path/to/file/file.log"

    self.task!.launchPath = "/bin/sh"
    self.task!.arguments = ["-c", argumentsString]

    let pipe = Pipe()

    task!.standardOutput = pipe
    task!.standardError = pipe

    pipe.fileHandleForReading.waitForDataInBackgroundAndNotify()

    task!.launch()
}

func commandTerminationHandler(_ task: Process) -> Void {
    // TODO: finish this
}

func commandOutputNotification(_ notification: Notification) {
    let fileHandle = notification.object as! FileHandle
    let data = fileHandle.availableData

    if data.count > 0 {
        processLogData(data:(String.init(data: data, encoding: String.Encoding.utf8)))
        fileHandle.waitForDataInBackgroundAndNotify()
    }
}

func processLogData(data:String?) {
    // Handle data String
}

如果正确打开此文件,则或多或少会自动执行此操作。NSDocument将告诉您需要重新读取该文件,因为该文件已更改。请在此处查看:谢谢,我们将检查并返回给您。