You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift获取iPhone本地文档、筛选文件类型及上传服务器的实现咨询

Hey there, let's break down solutions for your three UIDocumentPicker-related questions step by step, building on your existing code:

1. How to show only specific file types (docx, pdf, xlsx, images)

The key here is to use precise Uniform Type Identifiers (UTIs) in the documentTypes array—replace your current generic types with these targeted ones:

@IBAction func uploadNewResumeAction(_ sender: Any) {
    // UTIs mapped to your desired file types
    let allowedUTIs = [
        "org.openxmlformats.wordprocessingml.document", // docx
        "com.adobe.pdf", // pdf
        "org.openxmlformats.spreadsheetml.sheet", // xlsx
        "public.image" // Covers all system-recognized images (jpeg, png, etc.)
    ]
    
    let documentPicker = UIDocumentPickerViewController(
        documentTypes: allowedUTIs,
        in: .import
    )
    documentPicker.delegate = self
    present(documentPicker, animated: true, completion: nil)
}
  • If you need to restrict images to specific formats (e.g., only JPEG), swap public.image with public.jpeg or public.png.
  • Apple maintains an official list of system-provided UTIs if you need to verify other file types later.
2. How to access local docx files on iPhone (similar to Android's local file upload)

iOS uses a sandboxed file system, so you can't directly scan the entire device—but you can let users select local docx files via the Files app (which includes the "On My iPhone" storage). Adjust your code like this:

@IBAction func selectLocalDocxAction(_ sender: Any) {
    let docxUTI = "org.openxmlformats.wordprocessingml.document"
    let documentPicker = UIDocumentPickerViewController(
        documentTypes: [docxUTI],
        in: .open // Use .open to access the file directly, or .import to copy it to your app's sandbox
    )
    documentPicker.delegate = self
    present(documentPicker, animated: true, completion: nil)
}
  • .open gives your app temporary access to the original file; if you need ongoing access, you'll need to handle permission persistence.
  • The Files app's "On My iPhone" folder is where local files live—the picker will automatically display this location if enabled on the user's device.
3. How to get all local documents and upload to a server

iOS doesn't let apps automatically scan all local documents outside their sandbox (for privacy reasons), but you have two valid options:

Option 1: Let users select multiple documents manually

Enable multi-selection in the picker so users can choose all relevant files at once:

@IBAction func selectMultipleDocsAction(_ sender: Any) {
    let allowedUTIs = [
        "org.openxmlformats.wordprocessingml.document",
        "com.adobe.pdf",
        "org.openxmlformats.spreadsheetml.sheet",
        "public.image"
    ]
    
    let documentPicker = UIDocumentPickerViewController(
        documentTypes: allowedUTIs,
        in: .import
    )
    documentPicker.delegate = self
    documentPicker.allowsMultipleSelection = true // Turn on multi-select
    present(documentPicker, animated: true, completion: nil)
}

// Update your delegate to handle multiple files
extension SchoolRulesView: UIDocumentPickerDelegate {
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        for url in urls {
            print("Selected file: \(url.lastPathComponent)")
            // Call your upload logic for each file
            uploadFileToServer(url: url)
        }
    }
    
    // Keep single-selection support if needed
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
        uploadFileToServer(url: url)
    }
    
    // Example upload function (replace with your server integration)
    private func uploadFileToServer(url: URL) {
        do {
            let fileData = try Data(contentsOf: url)
            // Use URLSession to send fileData to your server endpoint
            // ...
        } catch {
            print("Error reading file: \(error.localizedDescription)")
        }
    }
}

Option 2: Scan files in your app's own sandbox

If you're targeting files stored in your app's Documents directory (files your app created or imported), you can programmatically scan that folder:

private func scanAppSandboxDocuments() {
    guard let documentsDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
        print("Could not access app's Documents directory")
        return
    }
    
    do {
        let fileURLs = try FileManager.default.contentsOfDirectory(
            at: documentsDir,
            includingPropertiesForKeys: nil,
            options: .skipsHiddenFiles
        )
        
        for url in fileURLs {
            print("Sandbox file: \(url.lastPathComponent)")
            uploadFileToServer(url: url)
        }
    } catch {
        print("Error scanning sandbox: \(error.localizedDescription)")
    }
}
  • Important: You can only access files in your app's sandbox without user permission. Any files outside of that require explicit user selection via the document picker.

内容的提问来源于stack exchange,提问作者saravanar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:26:27