gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 02:10:29 25 4
gpt4 key购买 nike

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

即使我更改文本文件中的值,它也会自动反射(reflect)在我的应用程序中。

有什么建议吗?

我正在使用 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_VNODE_EXTEND 事件,您可以在终端尝试此操作:

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

关于swift2 - 我们如何在没有任何用户输入的情况下从文本文件或服务器连续读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39040895/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com