我正在开发一个使用 CloudKit 来存储和检索图像文件的应用程序CKAsset
对象。通常情况下,这效果很好,而且我喜欢 CloudKit 的小学习曲线。不过,我偶尔会遇到一个特殊的问题,即图像要么完全颠倒,要么向左或向右 90° 存储。以下是存储不当的图像示例:
我用 iPhone 5s 纵向拍摄了这张照片(我没有将原始图像保存到我的设备上,因为我只想将其保存在云中,否则我也会将原始图像发布在这里。我想,因为它是坐在桌子旁的 MacBook Pro,您可以弄清楚图片的原始预期方向)。无论如何,我不仅对相机中的新鲜图像有这个问题,而且对从我的照片库中选择的图像也有这个问题。
这是我用来通过 CloudKit 存储图像的代码:
let newRecord:CKRecord = CKRecord(recordType: "ImageProject")
let imageData:NSData = UIImagePNGRepresentation(game.referenceImage)!
let path = self.documentsDirectoryPath.stringByAppendingPathComponent(self.imageDirectoryName)
imageURL = NSURL(fileURLWithPath: path)
imageData.writeToURL(imageURL, atomically: true)
UIImagePNGRepresentation(game.referenceImage)!.writeToFile(path, atomically: true)
let imageFile:CKAsset? = CKAsset(fileURL: NSURL(fileURLWithPath: path))
newRecord.setValue(imageFile, forKey: "referenceImage")
// Save the record into the public database
if let database = self.publicDatabase {
database.saveRecord(newRecord, completionHandler: { (record:CKRecord?, error:NSError?) in
// Check if there was an error
if error != nil {
NSLog((error?.localizedDescription)!)
}
else {
// There wasn't an error
dispatch_async(dispatch_get_main_queue()) {
if let savedRecord = record {
print("Image Successfully Saved")
}
}
}
})
}
这里的game
只是一个NSObject
我创建了名为SavedGame
,只存储变量,特别是对于这种情况referenceImage
as a UIImage
。我很确定我的检索过程不是问题,因为我注意到当我进入 CK 仪表板并在存储图像后下载图像时,它也会在那里旋转。以防万一,这是我用来检索图像的代码:
// Initialize the database and start the query
..........
for record in returnedRecords {
if let retrievedImage = record.objectForKey("referenceImage") as! CKAsset? {
let newGame:SavedGame = SavedGame()
if let data = NSData(contentsOfURL: retrievedImage.fileURL) {
newGame.referenceImage = UIImage(data: data)!
}
}
}
有人可以给我一些关于我可能在哪里犯错误的指导吗?这个问题根本不一致,很奇怪。我估计这种情况发生的概率可能是 5-10%。不知道是CK的问题,还是我的代码的问题。任何帮助将不胜感激。提前致谢!