这是一些适用于 iOS 的 Swift 代码,可以将二进制数据文件写入应用程序支持目录。其中部分内容的灵感来自 chrysAllwood 的回答。
/// Method to write a file containing binary data to the "application support" directory.
///
/// - Parameters:
/// - fileName: Name of the file to be written.
/// - dataBytes: File contents as a byte array.
/// - optionalSubfolder: Subfolder to contain the file, in addition to the bundle ID subfolder.
/// If this is omitted no extra subfolder is created/used.
/// - iCloudBackupForFolder: Specify false to opt out from iCloud backup for whole folder or
/// subfolder. This is only relevant if this method call results in
/// creation of the folder or subfolder, otherwise it is ignored.
/// - Returns: Nil if all OK, otherwise text for a couple of non-Error errors.
/// - Throws: Various errors possible, probably of type NSError.
public func writeBytesToApplicationSupportFile(_ fileName : String,
_ dataBytes : [UInt8],
optionalSubfolder : String? = nil,
iCloudBackupForFolder : Bool = true)
throws -> String? {
let fileManager = FileManager.default
// Get iOS directory for "application support" files
let appSupportDirectory =
fileManager.urls(for: .applicationSupportDirectory, in: .userDomainMask).first
if appSupportDirectory == nil {
return "Unable to determine iOS application support directory for this app."
}
// Add "bundle ID" as subfolder. This is recommended by Apple, although it is probably not
// necessary.
if Bundle.main.bundleIdentifier == nil {
return "Unable to determine bundle ID for the app."
}
var mySupportDirectory =
appSupportDirectory!.appendingPathComponent(Bundle.main.bundleIdentifier!)
// Add an additional subfolder if that option was specified
if optionalSubfolder != nil {
mySupportDirectory = appSupportDirectory!.appendingPathComponent(optionalSubfolder!)
}
// Create the folder and subfolder(s) as needed
if !fileManager.fileExists(atPath: mySupportDirectory.path) {
try fileManager.createDirectory(atPath: mySupportDirectory.path,
withIntermediateDirectories: true, attributes: nil)
// Opt out from iCloud backup for this subfolder if requested
if !iCloudBackupForFolder {
var resourceValues : URLResourceValues = URLResourceValues()
resourceValues.isExcludedFromBackup = true
try mySupportDirectory.setResourceValues(resourceValues)
}
}
// Create the file if necessary
let mySupportFile = mySupportDirectory.appendingPathComponent(fileName)
if !fileManager.fileExists(atPath: mySupportFile.path) {
if !fileManager.createFile(atPath: mySupportFile.path, contents: nil, attributes: nil) {
return "File creation failed."
}
}
// Write the file (finally)
let fileHandle = try FileHandle(forWritingTo: mySupportFile)
fileHandle.write(NSData(bytes: UnsafePointer(dataBytes), length: dataBytes.count) as Data)
fileHandle.closeFile()
return nil
}