iOS端将本地文件URL转换为可上传至WordPress网站的PDF/文档咨询
Hey there! Let’s tackle this file upload problem together. The key thing to note here is that the URL you get from UIDocumentPicker already points to the actual .doc/.pdf file—you don’t need to "convert" the URL itself to a different format. Instead, you need to read the file’s content and send it to your WordPress site via its REST API. Here’s a step-by-step solution:
Step 1: Gain Access to the Selected File
iOS uses security-scoped URLs for files outside your app’s sandbox, so you need to explicitly request access before reading the file:
guard let selectedFileURL = yourDocumentPickerURL else { return } // Request access to the file if selectedFileURL.startAccessingSecurityScopedResource() { defer { // Always release access when done selectedFileURL.stopAccessingSecurityScopedResource() } // Proceed to read and upload the file here } else { print("Failed to access the selected file") }
Step 2: Read the File into Data
Convert the file at the URL into a Data object—this is what you’ll send to WordPress:
do { let fileData = try Data(contentsOf: selectedFileURL) let fileName = selectedFileURL.lastPathComponent let mimeType = getMimeType(for: selectedFileURL) // We'll define this helper next uploadFileToWordPress(data: fileData, fileName: fileName, mimeType: mimeType) } catch { print("Error reading file: \(error.localizedDescription)") }
To get the correct MIME type for your file (critical for WordPress to recognize it), use this helper function:
import MobileCoreServices func getMimeType(for url: URL) -> String { let pathExtension = url.pathExtension as CFString guard let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, nil)?.takeRetainedValue(), let mimeType = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue() else { return "application/octet-stream" // Fallback if MIME type can't be determined } return mimeType as String }
Step 3: Upload to WordPress via REST API
WordPress’s REST API has a media endpoint (/wp-json/wp/v2/media) that accepts file uploads using multipart/form-data requests. You’ll need to handle authentication—use an application password from your WordPress admin for security, not your regular account password:
func uploadFileToWordPress(data: Data, fileName: String, mimeType: String) { guard let uploadURL = URL(string: "https://your-wordpress-site.com/wp-json/wp/v2/media") else { print("Invalid WordPress API URL") return } var request = URLRequest(url: uploadURL) request.httpMethod = "POST" // Set up Basic Authentication with your WordPress application password let username = "your-wordpress-username" let appPassword = "your-generated-application-password" // Create this in WP Admin > Users > Profile let loginCredentials = "\(username):\(appPassword)" if let loginData = loginCredentials.data(using: .utf8) { let base64Credentials = loginData.base64EncodedString() request.setValue("Basic \(base64Credentials)", forHTTPHeaderField: "Authorization") } // Configure multipart/form-data boundary let boundary = UUID().uuidString request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") // Build the request body var body = Data() // Add file part body.append("--\(boundary)\r\n".data(using: .utf8)!) body.append("Content-Disposition: form-data; name=\"file\"; filename=\"\(fileName)\"\r\n".data(using: .utf8)!) body.append("Content-Type: \(mimeType)\r\n\r\n".data(using: .utf8)!) body.append(data) body.append("\r\n--\(boundary)--\r\n".data(using: .utf8)!) request.httpBody = body // Send the upload request let task = URLSession.shared.dataTask(with: request) { data, response, error in if let error = error { print("Upload failed: \(error.localizedDescription)") return } guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else { print("Upload failed with invalid response") if let data = data, let errorMsg = String(data: data, encoding: .utf8) { print("WordPress error: \(errorMsg)") } return } // Upload successful! Parse the response to get media details if let data = data, let responseJSON = try? JSONSerialization.jsonObject(with: data) as? [String: Any] { print("File uploaded successfully! Media ID: \(responseJSON["id"] ?? "N/A")") // You can store this ID if you need to link the media to posts/pages later } } task.resume() }
Key Notes to Remember
- Permissions: Add appropriate usage descriptions to your
Info.plist(e.g.,NSDocumentsFolderUsageDescription) to explain why your app needs file access—iOS requires this. - Large Files: For large .pdf/.doc files, consider using background URL sessions to avoid interruptions if the app goes to the background.
- WordPress Settings: Ensure your WordPress site has the REST API enabled (it’s on by default in modern versions) and that your user account has permission to upload media.
内容的提问来源于stack exchange,提问作者Steven Roseman

