me icon indicating copy to clipboard operation
me copied to clipboard

学习 MacOS 开发 (Part 23: FileHandle)

Open nonocast opened this issue 2 years ago • 0 comments

讲一下通过swift写文件,如果不上AppStore就直接关掉sandbox,命令行的程序没有sandbox限制。后续如果打开AppStore就需要遵守一系列限制。

Case 1: string写入文件

// write string
let home = FileManager.default.homeDirectoryForCurrentUser
let filename = home.appendingPathComponent("/Desktop/clip.txt")
print(filename)

let text = "hello world"
do {
  try text.write(to: filename, atomically: true, encoding: .utf8)
} catch {
  print(error)
}

Case 2: NSData写入文件 (swift中对应Data)

let clip = home.appendingPathComponent("/Desktop/clip.h264")
let data = Data([0xFF, 0xFF, 0xFF, 0xFF])
do {
  try data.write(to: path)
} catch {
  print(error)
}

Case3: 多次写文件

var fileHandler: FileHandle?

try? FileManager.default.removeItem(at: clip)
if FileManager.default.createFile(atPath: clip.path, contents: nil, attributes: nil) {
  fileHandler = try FileHandle(forWritingTo: clip)
}

let header = Data([0x00, 0xFF])
let body = Data([0x11, 0x22, 0x33, 0x44])

if let f = fileHandler {
  defer { try! f.close() }
  do {
    try f.write(contentsOf: "CLIP".data(using: .ascii)!)
    try f.write(contentsOf: header)
    try f.write(contentsOf: body)
  } catch {}
}

通过xxd查看:

➜  Desktop xxd clip.h264 
00000000: 434c 4950 00ff 1122 3344                 CLIP..."3D
➜  Desktop 
➜  Desktop xxd -b clip.h264
00000000: 01000011 01001100 01001001 01010000 00000000 11111111  CLIP..
00000006: 00010001 00100010 00110011 01000100                    ."3D

nonocast avatar May 12 '22 23:05 nonocast