欢迎光临散文网 会员登陆 & 注册

Sandbox

2023-04-04 01:00 作者:小粉丝8  | 我要投稿

import SwiftUI


/*

 project navigator / Targets / Signing & Capabilities / App Sandbox:

  User Selected File: Read/Write;

  Downloads Folder: Read/Write;

 */


struct ContentView: View {

  @State private var fileDialogShown: Bool = false

  var body: some View {

    HStack {

      Button("Button1") { fileDialogShown = true }

        .fileImporter(isPresented: $fileDialogShown,

                allowedContentTypes: [.plainText])

        { result in

          guard let file = try? result.get() else { return }

          //Sandbox: User Selected File

          hello(file: file.path)

        }

      Button("Button2") { hello2() }

    }.frame(minWidth: 300, minHeight: 300)

  }

  

  func hello2(){

    //Sandbox: Downloads Folder, ~/Downloads

    let dir = FileManager.default.urls(for: .downloadsDirectory,

                       in: .userDomainMask).first!

    let file = dir.appendingPathComponent("hello.txt")

    hello(file: file.path)

  }

  

  func hello(file: String){

    var fp = fopen(file, "a")

    if fp == nil {

      perror("fopen")

      return;

    }

    fputs("hello1\n", fp)

    fputs("hello2\n", fp)

    fclose(fp)


    fp = fopen(file, "r")

    var buffer = [CChar](repeating: 0, count: 128)

    while fgets(&buffer, Int32(buffer.count), fp) != nil {

      print(String(cString: buffer), terminator: "")

    }

    fclose(fp);

  }

}


Sandbox的评论 (共 条)

分享到微博请遵守国家法律