如何使用Url初始化OutputStream?

如何使用Url初始化OutputStream?

问题描述:

我尝试创建一个OutputStream到一个应用程序组文件夹,这是为创建如下:如何使用Url初始化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 

此文件夹所在的路径,因为该行文件管理.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。

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()