Modifying metadata from an existing phasset seems inoperative

In my application, I want to make it possible for the user to set StarRating from 0 to 5 for any image that he has in his PhotoLibrary. My research shows that there are several ways to do this:

Save exif metadata with the new PHPhotoLibrary

Swift: Custom camera saves modified metadata with image

Writing a photo with metadata using Photokit

Most of these answers created a new photo. Now my fragment looks like this:

let options = PHContentEditingInputRequestOptions()
options.isNetworkAccessAllowed = true

self.requestContentEditingInput(with: options, completionHandler: {
            (contentEditingInput, _) -> Void in

    if contentEditingInput != nil {

        if let url = contentEditingInput!.fullSizeImageURL {
            if let nsurl = url as? NSURL {
                if let imageSource = CGImageSourceCreateWithURL(nsurl, nil) {
                    var imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) as Dictionary?
                    if imageProperties != nil {
                        imageProperties![kCGImagePropertyIPTCStarRating] = rating as AnyObject

                        let imageData = NSMutableData(contentsOf: url)
                        let image = UIImage(contentsOfFile: url.path)

                        let destination = CGImageDestinationCreateWithData(imageData!, CGImageSourceGetType(imageSource)!, 1, nil)

                        CGImageDestinationAddImage(destination!, image!.cgImage!, imageProperties! as CFDictionary)

                        var contentEditingOutput : PHContentEditingOutput? = nil

                        if CGImageDestinationFinalize(destination!) {
                            let archievedData = NSKeyedArchiver.archivedData(withRootObject: rating)
                            let identifier = "com.example.starrating"
                            let adjustmentData = PHAdjustmentData(formatIdentifier: identifier, formatVersion: "1.0", data: archievedData)

                            contentEditingOutput = PHContentEditingOutput(contentEditingInput: contentEditingInput!)
                            contentEditingOutput!.adjustmentData = adjustmentData
                            if imageData!.write(to: contentEditingOutput!.renderedContentURL, atomically: true) {
                                PHPhotoLibrary.shared().performChanges({
                                    let request = PHAssetChangeRequest(for: self)
                                    request.contentEditingOutput = contentEditingOutput
                                }, completionHandler: {
                                    success, error in
                                    if success && error == nil {
                                        completion(true)
                                    } else {
                                        completion(false)
                                    }
                                })
                            }
                        } else {
                            completion(false)
                        }

                    }
                }
            }
        }
    }
})

Now that I want to read the metadata from PHAsset, I again request ContentEditingInput and do the following:

if let url = contentEditingInput!.fullSizeImageURL {
    if let nsurl = url as? NSURL {
        if let imageSource = CGImageSourceCreateWithURL(nsurl, nil) {
            if let imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) as Dictionary? {

                if let starRating = imageProperties[kCGImagePropertyIPTCStarRating] as? Int {
                    rating = starRating
                }
            }
        }
    }
}

But I never get my rating because it says the value imageProperties[kCGImagePropertyIPTCStarRating]is zero.

, , .

, - , , .

, PHAsset MediaType .video? AVAssetWriter AVExportSession, . :

var exportSession = AVAssetExportSession(asset: asset!, presetName: AVAssetExportPresetPassthrough)
exportSession!.outputURL = outputURL
exportSession!.outputFileType = AVFileTypeQuickTimeMovie
exportSession!.timeRange = CMTimeRange(start: start, duration: duration)

var modifiedMetadata = asset!.metadata

let metadataItem = AVMutableMetadataItem()
metadataItem.keySpace = AVMetadataKeySpaceQuickTimeMetadata
metadataItem.key = AVMetadataQuickTimeMetadataKeyRatingUser as NSCopying & NSObjectProtocol
metadataItem.value = rating as NSCopying & NSObjectProtocol

modifiedMetadata.append(metadataItem)

exportSession!.metadata = modifiedMetadata


exportSession!.exportAsynchronously(completionHandler: {
    let status = exportSession?.status
    let success = status == AVAssetExportSessionStatus.completed
    if success {
        do {
            let sourceURL = urlAsset.url
            let manager = FileManager.default
            _ = try manager.removeItem(at: sourceURL)
            _ = try manager.moveItem(at: outputURL, to: sourceURL)
        } catch {
            LogError("\(error)")
            completion(false)
        }
    } else {
        LogError("\(exportSession!.error!)")
        completion(false)
    }
})
+4
1

, , . , StarRating . IPTC. . , imageProperties, , .

func setIPTCStarRating(imageProperties : NSMutableDictionary, rating : Int) {
    if let iptc = imageProperties[kCGImagePropertyIPTCDictionary] as? NSMutableDictionary {
        iptc[kCGImagePropertyIPTCStarRating] = String(rating)
    } else {
        let iptc = NSMutableDictionary()
        iptc[kCGImagePropertyIPTCStarRating] = String(rating)
        imageProperties[kCGImagePropertyIPTCDictionary] = iptc
    }
}


func getIPTCStarRating(imageProperties : NSMutableDictionary) -> Int? {
    if let iptc = imageProperties[kCGImagePropertyIPTCDictionary] as? NSDictionary {
        if let starRating = iptc[kCGImagePropertyIPTCStarRating] as? String {
            return Int(starRating)
        }
    }
    return nil
}

imageProperties, , , , . , CGImageDestinationAddImage()

if let mutableProperties = imageProperties.mutableCopy() as? NSMutableDictionary {
    setIPTCStarRating(imageProperties:mutableProperties, rating:rating)
}

, UIImage. CGImageDestinationAddImageFromSource() CGImageDestinationAddImage(), imageSource UIImage.

+1

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


All Articles