【问题标题】:How to initialise an OutputStream with a Url?如何使用 Url 初始化 OutputStream?
【发布时间】:2017-11-06 01:27:46
【问题描述】:

我尝试创建一个OutputStream到一个应用组文件夹,创建如下:

 func createProjectDirectoryPath(path:String) -> String
    {
        let containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.xyz")
        let logsPath = containerURL!.appendingPathComponent(path)
        NSLog("12345- folder path: %@", logsPath.path)

        do {
            try FileManager.default.createDirectory(atPath: logsPath.path, withIntermediateDirectories: true, attributes: nil)
        } catch let error as NSError {
            NSLog("12345- Unable to create directory %@", error.debugDescription)
        }
        return logsPath.path
    }

这个函数给了我这样的路径

/private/var/mobile/Containers/Shared/AppGroup/40215F20-4713-4E23-87EF-1E21CCFB45DF/pcapFiles

此文件夹存在,因为 FileManager.default.fileExists(path) 行返回 true。下一步是将生成的文件名附加到路径中,我正在这里

let urlToFile = URL(string: createProjectDirectoryPath(path: "pcapFiles").appending("/\(filename)"))

这给了我正确的新路径

/private/var/mobile/Containers/Shared/AppGroup/40215F20-4713-4E23-87EF-1E21CCFB45DF/pcapFiles/39CC2DB4-A6D9-412E-BAAF-2FAA4AD70B22.pcap

如果我调用此行,ostream 始终为零

let ostream = OutputStream(url: urlToFile!, append: false)

我错过了什么吗? OutputStream 应该在此路径上创建文件,但由于未知原因,这是不可能的。

PS:AppGroup 在 Capabilities 和开发者控制台中启用。

【问题讨论】:

    标签: ios swift file stream ios-app-group


    【解决方案1】:

    您的createProjectDirectoryPath() 函数返回一个文件路径, 因此您必须使用 URL(fileURLWithPath:) 将其转换为 URL。或者,修改您的函数以返回 URL

    func createProjectDirectoryPath(path:String) -> URL? {
        let containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.xyz")
        let logsURL = containerURL!.appendingPathComponent(path)
        do {
            try FileManager.default.createDirectory(at: logsURL, withIntermediateDirectories: true)
        } catch let error as NSError {
            NSLog("Unable to create directory %@", error.debugDescription)
            return nil
        }
        return logsURL
    }
    

    此外,您必须在所有 Stream 对象上调用 open() 它们可以使用,如果文件不存在,这也会创建文件 之前:

    guard let logsURL = createProjectDirectoryPath(path: "pcapFiles") else {
        fatalError("Cannot create directory")
    }
    let urlToFile = logsURL.appendingPathComponent(filename) 
    guard let ostream = OutputStream(url: urlToFile, append: false) else {
        fatalError("Cannot open file")
    }
    ostream.open()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-24
      • 1970-01-01
      • 2020-08-02
      • 2012-02-17
      相关资源
      最近更新 更多