swiftPunk
swiftPunk

Reputation: 1

How to Create a New Folder in iCloud Documents Inside My App Name in Swift/SwiftUI?

I want to create a new folder in iCloud Documents inside my app's folder. I used the following code, and I have added iCloud from Xcode's Signing & Capabilities. However, I am getting the following error in the Xcode console: Error: Could not access iCloud container.

Here is the code I'm using:

import SwiftUI

struct ContentView: View {
    @State private var folderName = "NewFolder" // Folder name from a string
    
    var body: some View {
        VStack {
            Button("Create Folder") {
                createFolderInICloud(folderName: folderName)
            }
        }
        .padding()
    }
    
    func createFolderInICloud(folderName: String) {
        // Get the URL for the iCloud container (replace "com.yourcompany.yourapp" with your app's iCloud identifier)
        guard let iCloudURL = fileManagerURLForICloud() else {
            print("Error: Could not access iCloud container")
            return
        }
        
        // Combine the iCloud URL with the desired folder name
        let folderURL = iCloudURL.appendingPathComponent(folderName)
        
        do {
            // Check if the folder already exists
            if !FileManager.default.fileExists(atPath: folderURL.path) {
                // Create the folder
                try FileManager.default.createDirectory(at: folderURL, withIntermediateDirectories: true, attributes: nil)
                print("Folder created successfully at: \(folderURL.path)")
            } else {
                print("Folder already exists at: \(folderURL.path)")
            }
        } catch {
            print("Failed to create folder: \(error)")
        }
    }
    
    func fileManagerURLForICloud() -> URL? {
        let fileManager = FileManager.default
        // Access the iCloud container using the app's iCloud identifier (replace with your actual iCloud container identifier)
        return fileManager.url(forUbiquityContainerIdentifier: "com.mycompany.myapp")?.appendingPathComponent("Documents")
    }
}

Could someone help me figure out why I'm getting this error and how I can fix it? I believe the iCloud container might not be set up correctly, but I have enabled the correct capabilities.

enter image description here

Upvotes: 0

Views: 123

Answers (0)

Related Questions