最后,我弄清楚了如何使所有东西按我需要的方式工作。对我最大的帮助是发现可以将CFDictionary转换为NSMutableDictionary。
这是我的最终代码:
如您所见,我向EXIF字典中添加了一个属性,用于数字化日期,并更改了方向值。
private func snapPhoto(success: (UIImage, NSMutableDictionary) -> Void, errorMessage: String -> Void) {
guard !self.stillImageOutput.capturingStillImage,
let videoConnection = stillImageOutput.connectionWithMediaType(AVMediaTypeVideo) else { return }
videoConnection.fixVideoOrientation()
stillImageOutput.captureStillImageAsynchronouslyFromConnection(videoConnection) {
(imageDataSampleBuffer, error) -> Void in
guard imageDataSampleBuffer != nil && error == nil else {
errorMessage("Couldn't snap photo")
return
}
let data = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer)
let rawMetadata = CMCopyDictionaryOfAttachments(nil, imageDataSampleBuffer, CMAttachmentMode(kCMAttachmentMode_ShouldPropagate))
let Metadata = CFDictionaryCreateMutableCopy(nil, 0, rawMetadata) as NSMutableDictionary
let exifData = Metadata.valueForKey(kCGImagePropertyExifDictionary as String) as? NSMutableDictionary
exifData?.setValue(NSDate().toString("yyyy:MM:dd HH:mm:ss"), forKey: kCGImagePropertyExifDateTimeDigitized as String)
Metadata.setValue(exifData, forKey: kCGImagePropertyExifDictionary as String)
Metadata.setValue(1, forKey: kCGImagePropertyOrientation as String)
guard let image = UIImage(data: data)?.fixOrientation() else {
errorMessage("Couldn't create image")
return
}
success(image, Metadata)
}
}
还有我用于保存带有元数据的图像的最终代码:
我讨厌很多警卫声明,但这比强制展开要好。
func saveImage(withMetadata image: UIImage, Metadata: NSMutableDictionary) {
let filePath = "\(self.documentsPath)/image1.jpg"
guard let jpgData = UIImageJPEGRepresentation(image, 1) else { return }
// Add Metadata to jpgData
guard let source = CGImageSourceCreateWithData(jpgData, nil),
let uniformTypeIdentifier = CGImageSourceGetType(source) else { return }
let finalData = NSMutableData(data: jpgData)
guard let destination = CGImageDestinationCreateWithData(finalData, uniformTypeIdentifier, 1, nil) else { return }
CGImageDestinationAddImageFromSource(destination, source, 0, Metadata)
guard CGImageDestinationFinalize(destination) else { return }
// Save image that Now has Metadata
self.fileService.save(filePath, data: finalData)
}
这是我的更新save
方法(与我编写此问题时使用的方法不完全相同,因为我已更新到Swift 2.3,但概念相同):
public func save(fileAt path: NSURL, with data: NSData) throws -> Bool {
guard let pathString = path.absoluteString else { return false }
let directory = (pathString as NSString).stringByDeletingLastPathComponent
if !self.fileManager.fileExistsAtPath(directory) {
try self.makeDirectory(at: NSURL(string: directory)!)
}
if self.fileManager.fileExistsAtPath(pathString) {
try self.delete(fileAt: path)
}
return self.fileManager.createFileAtPath(pathString, contents: data, attributes: [NSFileProtectionKey: NSFileProtectionComplete])
}