Home > Software design >  iOS Error on uploading pdf file to server - Swift Xcode 13
iOS Error on uploading pdf file to server - Swift Xcode 13

Time:03-01

I am working on uploading pdf file to server using UIDocumentPicker. It selects the file correctly but while fetching the file content it is throwing this error:

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"}}

The error is telling me there seems to be a permission problem. I searched around but have not found any working solution. Here my code for uploading file to server.

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()
}

Error shows up on this line:

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

Thanks in Advance Nabeel

CodePudding user response:

Try below way to fix issue:

startAccessingSecurityScopedResource will help to fix issue

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()
        }
  • Related