iOS 将 pdf 文件上传到服务器时出错 - Swift Xcode 13

iOS Error on uploading pdf file to server - Swift Xcode 13

我正在使用 UIDocumentPicker 将 pdf 文件上传到服务器。它正确选择了文件,但在获取文件内容时抛出此错误:

Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=NSCocoaErrorDomain Code=257 "The file “file-sample_150kB.pdf” couldn’t be opened because you don’t have permission to view it." UserInfo={NSFilePath=/private/var/mobile/Library/Mobile Documents/com~apple~CloudDocs/Downloads/file-sample_150kB.pdf, NSUnderlyingError=0x28225c5a0 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}

错误告诉我似乎存在权限问题。我四处搜索但没有找到任何可行的解决方案。 这是我将文件上传到服务器的代码。

func uploadDocumentRequest(targetVC : UIViewController, args: [String : String], url: URL)
{
    let boundary = generateBoundaryString()

    var body = Data()
    for (key, value) in args
    {
        body.append(Data("--\(boundary)\r\n".utf8))
        body.append(Data("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n".utf8))
        body.append(Data("\(value)\r\n".utf8))
    }

    let filePathKey = "file"
    let filename = "doc_file.pdf"
    let fileData: Data = try! Data(contentsOf: url)
    let mimetype = "application/pdf"

    body.append(Data("--\(boundary)\r\n".utf8))
    body.append(Data("Content-Disposition: form-data; name=\"\(filePathKey)\"; filename=\"\(filename)\"\r\n".utf8))
    body.append(Data("Content-Type: \(mimetype)\r\n\r\n".utf8))
    body.append(fileData)
    body.append(Data("\r\n".utf8))
    body.append(Data("--\(boundary)--\r\n".utf8))

    let url = URL(string: BASE_URL + "scripts/ajaxEntryPoint.php")!
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
    request.httpBody = body

    let configuration = URLSessionConfiguration.default
    let session = URLSession(configuration: configuration, delegate: self, delegateQueue: OperationQueue.main)

    let task = session.dataTask(with: request as URLRequest, completionHandler: {
        (data, response, error) in

        guard let _:Data = data else
        {
            return
        }

        let json:Any?

        do
        {
            json = try JSONSerialization.jsonObject(with: data!, options: [])
        }
        catch
        {
            return
        }

        guard let server_response = json as? NSDictionary else
        {
            return
        }

        print(server_response)
    })

    task.resume()
}

此行出现错误:

let fileData: Data = try! Data(contentsOf: url)

提前致谢 纳比尔

尝试以下方法解决问题:

startAccessingSecurityScopedResource 将有助于解决问题

if var firstDoc = urls.first, firstDoc.startAccessingSecurityScopedResource() {
            defer {
                DispatchQueue.main.async {
                    firstDoc.stopAccessingSecurityScopedResource()
                }
            }
            do {
                let data = try Data.init(contentsOf: firstDoc)
                let dest = URL(type: .doc, fileName: firstDoc.lastPathComponent)
                try data.write(to: dest)
                firstDoc = dest
            } catch {
                debugPrint("Error : ", error)
            }
  
            self.openDocumentController()
        }