วิธีเรียกใช้ไบนารีแบบฝังในแอพ SwiftUI Mac

Aug 19 2020

ฉันกำลังพยายามพัฒนาโปรแกรมตรวจสอบ XML ที่เรียบง่ายโดยใช้ XIDEL

นี่คือรหัส SwiftUI ของฉันที่เรียกใช้ไบนารี XIDEL ที่ฝังไว้ แต่ฉันไม่สามารถหาวิธีส่ง XML ที่ควรตรวจสอบ เป้าหมายของฉันคือเลือกไฟล์ XML จากคอมพิวเตอร์ของฉันและแสดงผลลัพธ์ XIDEL ในมุมมองเนื้อหาภายในแอปของฉัน

struct ContentView: View {

@State var message = "Hello, World!"
@State var isRunning = false

var body: some View {
    VStack {
        Text("XML Validator")
            .font(.largeTitle)
            .padding()
        HStack {
            TextField("Message", text: $message)
                .padding(.leading)
            Button(action: {

                let task = Process()
                let bundle = Bundle.main
                let execURL = bundle.url(forResource: "xidel", withExtension: nil)
                guard execURL != nil else {
                    print("XIDEL executable could not be found!")
                    return
                }
                task.executableURL = execURL!
                task.arguments = ["-e=//recipe/flavor1/text() my.xml"]
                do {
                    try task.run()
                    print("XIDEL executed successfully!")
                    self.isRunning = true
                } catch {
                    print("Error running XIDEL: \(error)")
                    self.isRunning = false
                }
                                    
            }) {
                Text("Validate")
            }.disabled(isRunning)
                .padding(.trailing)
        }
    }.frame(maxWidth: .infinity, maxHeight: .infinity)
}

}

คำตอบ

1 Asperi Aug 19 2020 at 18:05

ลองทำดังต่อไปนี้

    guard let path = Bundle.main.path(forResource: "my", ofType: "xml") else {
       print("my.xml could not be found!")
       return 
    }
    task.arguments = ["-e=//recipe/flavor1/text()", path]