Error on uploading pdf file to server

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

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

Answered by Engineer in 706253022

Are you calling startAccessingSecurityScopedResource / stopAccessingSecurityScopedResource on the URL which you receive from UIDocumentPicker?

See the Requirements section here: https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/DocumentPickerProgrammingGuide/AccessingDocuments/AccessingDocuments.html#//apple_ref/doc/uid/TP40014451-CH2-SW3

And the Discussion section here: https://developer.apple.com/documentation/uikit/uidocumentpickerdelegate/2902364-documentpicker

Accepted Answer

Are you calling startAccessingSecurityScopedResource / stopAccessingSecurityScopedResource on the URL which you receive from UIDocumentPicker?

See the Requirements section here: https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/DocumentPickerProgrammingGuide/AccessingDocuments/AccessingDocuments.html#//apple_ref/doc/uid/TP40014451-CH2-SW3

And the Discussion section here: https://developer.apple.com/documentation/uikit/uidocumentpickerdelegate/2902364-documentpicker

Error on uploading pdf file to server
 
 
Q