PHAsset: saving a new image with metadata

I use UIImagePickerController to allow the user to take a picture with the camera. When the delegate called, I want to save the image in the photo library / camera clip that I use with PHAssetChangeRequest. The problem in the documentation says that I can use a dictionary from UIImagePickerControllerMediaMetadata to include this as metadata, but PHAssetChangeRequest does not seem to have a parameter for this. How to include this metadata when saving? Thanks!

+4
source share
2 answers

From what I can understand by reading the source, what Apple means in metadata is the properties of an asset.

open var pixelWidth: Int { get }
open var pixelHeight: Int { get }
open var creationDate: Date? { get }
open var modificationDate: Date? { get }
open var location: CLLocation? { get }
open var duration: TimeInterval { get }
open var isHidden: Bool { get }

Other metadata can be found in the image by accessing the CGImage properties.

0
source

You can use PHAssetCreationRequest. To use PHAssetCreationRequest, you combine imageData and metadata, and then write imageDataWithMetadata to an album. Like this:

if let imageDataWithMetadata = self.writeMetadata(metadata, into: imageData) {
    self.saveImageDataForiOS9(imageDataWithMetadata)
}

func saveImageDataForiOS9(_ data: Data) {
    var newImageIdentifier: String!

    PHPhotoLibrary.shared().performChanges({
        if #available(iOS 9.0, *) {
            let assetRequest = PHAssetCreationRequest.forAsset()
            assetRequest.addResource(with: .photo, data: data, options: nil)
            newImageIdentifier = assetRequest.placeholderForCreatedAsset!.localIdentifier
        } else {
            // Fallback on earlier versions
        }
    }) { (success, error) in
        DispatchQueue.main.async(execute: {
            if success, let newAsset = PHAsset.fetchAssets(withLocalIdentifiers: [newImageIdentifi
                // ...
            } else {
                // ...
            }
        })

    }
}

For iOS 8, you can use ALAssetsLibraryto save a new image with metadata:

func saveImageDataForiOS8(_ imageData: Data, _ metadata: Dictionary<AnyHashable, Any>?) {
    let library = ALAssetsLibrary()
    library.writeImageData(toSavedPhotosAlbum: imageData, metadata: metadata, completionBlock: { (newURL, error) in
        if let _ = error {
            // ...
        } else {
            if let newAsset = PHAsset.fetchAssets(withALAssetURLs: [newURL!], options: nil).firstObject {
                // ...
            }
        }
    })
}

So finally, you will have this code:

func saveImage(_ imageData: Data, metadata: Dictionary<AnyHashable, Any>?) {
    if #available(iOS 9.0, *) {
        if let metadata = metadata {
            if let imageDataWithMetadata = self.writeMetadata(metadata, into: imageData) {
                self.saveImageDataForiOS9(imageDataWithMetadata)
            } else {
                self.saveImageDataForiOS9(imageData)
            }
        } else {
            self.saveImageDataForiOS9(imageData)
        }
    } else {
        self.saveImageDataForiOS8(imageData, metadata)
    }
}

func saveImageDataForiOS8(_ imageData: Data, _ metadata: Dictionary<AnyHashable, Any>?) {
    let library = ALAssetsLibrary()
    library.writeImageData(toSavedPhotosAlbum: imageData, metadata: metadata, completionBloc
        if let _ = error {
            // ...
        } else {
            if let newAsset = PHAsset.fetchAssets(withALAssetURLs: [newURL!], options: nil).
                // ...
            }
        }
    })
}

func saveImageDataForiOS9(_ data: Data) {
    var newImageIdentifier: String!

    PHPhotoLibrary.shared().performChanges({
        if #available(iOS 9.0, *) {
            let assetRequest = PHAssetCreationRequest.forAsset()
            assetRequest.addResource(with: .photo, data: data, options: nil)
            newImageIdentifier = assetRequest.placeholderForCreatedAsset!.localIdentifier
        } else {
            // Fallback on earlier versions
        }
    }) { (success, error) in
        DispatchQueue.main.async(execute: {
            if success, let newAsset = PHAsset.fetchAssets(withLocalIdentifiers: [newImageId
                // ...
            } else {
                // ...
            }
        })

    }
}

internal func writeMetadata(_ metadata: Dictionary<AnyHashable, Any>, into imageData: Data) 
    let source = CGImageSourceCreateWithData(imageData as CFData, nil)!
    let UTI = CGImageSourceGetType(source)!

    let newImageData = NSMutableData()
    if let destination = CGImageDestinationCreateWithData(newImageData, UTI, 1, nil) {
        CGImageDestinationAddImageFromSource(destination, source, 0, metadata as CFDictionar
        if CGImageDestinationFinalize(destination) {
            return newImageData as Data
        } else {
            return nil
        }
    } else {
        return nil
    }
}
0
source

Source: https://habr.com/ru/post/1617926/


All Articles