Mount Network Drive SwiftUI

    import SwiftUI

    struct ContentView: View {
    
    @State private var username: String = ""
    @State private var password: String = ""
    @State private var connectionStatus: String = ""
    
    @discardableResult func shell(_ command: String, withPassword password: String) -> (String?,       Int32) {
    // Erstelle neuen Prozess und lege den Pfad fest
    let task = Process()
    task.launchPath = "/bin/bash"
        
    // Konstruiere das Kommando zur Nutzung von sudo mit Passwort
    let sudoCommand = "echo (password) | sudo -S (command)"
        
    // "-c" Argument lässt nachfolgenden Befehl als Bash-Befehl ausführen
    task.arguments = ["-c", sudoCommand]
        
    // Pipe für Ausgabe und Fehlermeldung
    let pipe = Pipe()
    task.standardOutput = pipe
    task.standardError = pipe
    // Starte Prozess
    task.launch()
    // Lese gesamte Ausgabe
    let data = pipe.fileHandleForReading.readDataToEndOfFile()
    // Konvertiere Ausgabe in einen String, falls möglich
    let output = String(data: data, encoding: .utf8)
    task.waitUntilExit()
    return (output, task.terminationStatus)
    }
    
    var body: some View {
    VStack {
    Text("Connect Network Drive")
    .font(.title)
    .bold()
    .padding()
           
    TextField("Username", text: $username)
    .textFieldStyle(RoundedBorderTextFieldStyle())
    .padding()
            
    SecureField("Password", text: $password)
               .textFieldStyle(RoundedBorderTextFieldStyle())
                .padding()
            
            Button(action: {
                runScript()
            }) {
                Text("Connect").font(.body)
            }
            .padding()
            
            Text(connectionStatus)
                .foregroundColor(.red)
                .padding()
            
            Spacer()
        }
        .padding()
    }
    
    func runScript() {
        // Pfad zum Mountpunkt und zum Netzlaufwerk
        let mountPoint = "~/Desktop/DriveH"
        let networkPath = "//(username):(password)@server/Pfad" // Passen Sie den Netzwerkpfad an
        
        // Erstellen des Verzeichnisses, falls es nicht existiert
        let mkdirCommand = "mkdir -p (mountPoint)"
        let mountCommand = "mount_smbfs (networkPath) (mountPoint)"
        
        // Führen Sie den Befehl zum Erstellen des Verzeichnisses aus
        let mkdirResult = shell(mkdirCommand, withPassword: password)
        if mkdirResult.1 != 0 {
            connectionStatus = "Failed to create mount point: (mkdirResult.0 ?? "Unknown error")"
            return
        }
        
        // Führen Sie den Befehl zum Mounten des Netzlaufwerks aus
        let mountResult = shell(mountCommand, withPassword: password)
        if mountResult.1 == 0 {
            connectionStatus = "Network drive connected successfully."
        } else {
            connectionStatus = "Failed to connect network drive: (mountResult.0 ?? "Unknown error")"
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}


I am trying to mount a network drive via a Swift UI. But unfortunately I only get the following response “Operation not permitted”, can anyone help me here?
I have already tried to run it as “sudo”, but that didn’t work properly either. But it could also be that I programmed it incorrectly.
I have already tried to mount it via a bash script so that the button calls the bash script, but unfortunately this resulted in the same error message.

New contributor

munkimichi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

3

It’s not allowed to run shell scripts in a sandbox environment. Well, it is possible under certain circumstances but Process is strictly forbidden.

However NetFSMountURLAsync in the NetFS framework does work in a sandbox if you specify the mount point somewhere in the application container for example in the Application Support folder.

Important: You have to enable Outgoing Connections (Client) in the sandbox settings.

This is an example

import NetFS

var requestID : AsyncRequestID?
let url = URL(string: "smb://MyServer.local/myvolume")!
let userName = "user"
let password = "pass"   
let mountPoint = URL.applicationSupportDirectory

NetFSMountURLAsync(url as CFURL,
                   mountPoint as CFURL,
                   userName as CFString,
                   password as CFString,
                   nil,
                   nil,
                   &requestID,
                   DispatchQueue.global()
) { status, requestID, mountpoints in
    if status != 0 && status != -128 {
        print("Shared Volume mount at (url.path) failed with status: (status)")
    }
}

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật