I am a little lost on my quest to -
I have managed to download the CKAsset and display the contents in a UIWebView, however I am stumbling over steps 2 and 3, I have a filename from a String, and despite trying a variety of WriteToFile combinations I receive errors.
My code is thus :
let filename = record.object(forKey: "materialsFilename")
if materialsType == "PDF" || materialsType == "pdf" {
if let asset1 = record.object(forKey: "materialsFile") as? CKAsset {
let doc1Data : NSData? = NSData(contentsOf:asset1.fileURL)
let path = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(filename as! String)
let contentsOfFile = doc1Data
var error: NSError?
// Write File
if contentsOfFile.writeToFile(path, atomically: true, encoding: String.Encoding.utf8, error: &error) == false {
if let errorMessage = error {
print("Failed to create file")
print("\(errorMessage)")
}
} else {
print("File \(filename) created at tmp directory")
}
This version presents the error -
Cannot invoke 'writeToFile' with an argument list of type '(URL?, atomically: Bool, encoding: String.Encoding, error: inout NSError?)'
The temporary file once created will be passed to a UIActivityViewController, to print / email / airdrop the PDF, having only a CKAsset name, the the UIActivityViewController cannot associate the file type to any of the users installed apps, save for print.
After a little head scratching and reviewing my choices following the pointers above, I changed tack and didn't really need to write to a file, just rename the CKAsset, which I achieved with the following script -
let materialsType = record.object(forKey: "materialsType") as! String
let filename = record.object(forKey: "materialsFilename") as! String
if materialsType == "PDF" || materialsType == "pdf" {
if let asset1 = record.object(forKey: "materialsFile") as? CKAsset {
let doc1Data : Data? = Data(contentsOf:asset1.fileURL) as Data?
let fileURL = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(filename)
self.materialsWebView.load(doc1Data! as Data, mimeType: "application/pdf", textEncodingName: "UTF-8", baseURL: NSURL() as URL)
self.filenameURL = [(fileURL)]
}
The key seemed to hinge on two lines -
let fileURL = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(filename)
and
self.filenameURL = [(fileURL)]
Which generates the filename for the UIActivityViewController and thus opens up the access to a number of additional Apps.