Get Filename From PHAsset swift 5 IOS13 - swift5

My Question is how we get file Name From PHAsset Which Are Picked By gallery
var allSmallPic: [PHAsset] = []
PHImageManager.default().requestImage(for: allSmallPic[indexPath.row], targetSize: PHImageManagerMaximumSize, contentMode: .aspectFit, options: nil) { (image, info) in
cell.ImageVieww.image = image
cell.Labell.text = "\(String(describing: info!))"
print(info!)
}

let resource1 = PHAssetResource.assetResources(for:self.allSmallPic[indexPath.row])
print("Get resources\(resource1)")
cell.Labell.text = resource1[0].originalFilename

As you Know PHAsset is representation of an image, video, or Live Photo in the Photos library.
So I want to show the file names into my tableViewCell Like this
when no results found i'm start read documentations and i found PHAssetResource and they help me to Get image name
let resource1 = PHAssetResource.assetResources(for:self.allSmallPic[indexPath.row])
print("Get resources\(resource1)")
cell.Labell.text = resource1[0].originalFilename
The allSmallPic is global array which store PHAsset

Related

How to grab all metadata from any image?

I have been searching google and could not find a solution for my problem. I have some code that grabs metadata from images the user picks from the image picker. The problem is that my code doesn't grab ALL metadata from HEIC and RAW images. I set up some print statements to find out which data my code doesn't grab from HEIC.
Manufacturer not found
Camera model not found
Camera software not found
Aperture not found
Focal length not found
ISO not found
Shutter speed not found
//And this is my metadata extracting code block
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let image = info[.originalImage] as? UIImage
let url = info[.imageURL]
let optionalImageData = try? Data(contentsOf: url as! URL)
guard let imageData = optionalImageData else { return }
let source: CGImageSource = CGImageSourceCreateWithData(imageData as CFData, nil)!
let metadata = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [AnyHashable: Any]
print(metadata!)
self.dismiss(animated: true, completion: nil)
}
I'm going to guess that you have not obtained user permission to access the photos library. You are allowed to present the picker even so, but the information that you can receive in response is very limited. If you have user permission, you can receive the image as a PHAsset and you can get the desired metadata from the photos library.

get Image from PHAsset issue to detect updates on images

I'm currently managing a PHAsset with multiple Pictures (from an Album my application is creating), I'm able to display it without any problem.
For each picture of my PHAsset, I'm calculating the hash of each pictures in my app.
But If I'm modifying the picture out of my app (through the Photos, I'm changing the color of the picture for example) I'm not able to detect the update, if I'm calculating the hash one more time of the PHAsset pictures while my app is resumed, the update is not detected, the hashes remains the same...
Here is the code to get image from PHAsset:
var img: UIImage?
let manager = PHImageManager.default()
let options = PHImageRequestOptions()
options.version = .original
options.isSynchronous = true
manager.requestImageData(for: asset, options: options) { (data, _, _, _) in
if let data = data{
img = UIImage(data: data)
}
}
return img
I'm using this function while adding the picture (to calculate the hash), and when I need to check the hash of the PHasset's pictures, I'm retrieving the PHAssetCollection by using
let collection = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)
but no changes are detected...may be I need to ask for a refresh of the PHAssetCollection to retrieve the changes on the pictures ?
Am I missing something ?
Just to be clear, I'm calculating the hash of the Image with the following:
//function described just above
let img = getSavedImageFromPHAsset(asset: myAsset)!
let img_hash = img.sha256()
//I'm comparing the hashes with this value
func sha256(data: Data) -> Data {
var digestData = Data(count: Int(CC_SHA256_DIGEST_LENGTH))
_ = digestData.withUnsafeMutableBytes {digestBytes in
data.withUnsafeBytes {messageBytes in
CC_SHA256(messageBytes, CC_LONG(data.count), digestBytes)
}
}
return digestData
}
I assumed that as soon as an image linked to the PHAsset has been changed, I'm able to detect its modification (I can see the picture updated on my app's screen, but hash calculated is still the same)
Try the following:
options.version = .current
instead of
options.version = .original
Your code will always return the original, unedited photo/video. .current returns the same photo that you see in the iOS Photos App.

Read Gallery Video in Custom Size

How could I get a video from Gallery(Photos) in custom format and size.
for example I want to read a video in 360p.
I used below code to get video data but apple said it doesn't guarantee to read it in lowest quality.
It's a PHAsset extension, so self refering to a PHAsset object.
var fileData: Data? = nil
let manager = PHImageManager.default()
let options = PHVideoRequestOptions()
options.isNetworkAccessAllowed = true
options.deliveryMode = .fastFormat
manager.requestAVAsset(forVideo: self, options: options) {
(asset: AVAsset?, audioMix: AVAudioMix?, _) in
if let avassetURL = asset as? AVURLAsset {
guard let video = try? Data(contentsOf: avassetURL.url) else {
print("reading video failed")
return
}
fileData = video
}
}
There is a simple reason it can't be guaranteed: The file in 360p might not be on the device or in the cloud. So the Photos framework will deliver a format nearest to what you request. If you want exactly 360p, I would recommend you reencode the video you get from the photos framework yourself.

How to get a PHAsset of the video from a video URL?

How do I get a PHAsset of a captured video, if I've got only a video URL? My problem is that I know how to get URL of a video from PHAsset, but don't understand how to get PHAsset from video URL.
This is what I tried to do, but it didn't work. It's not for a video, but for a photo...So Idk how to make it for a video.
let imgData = NSData(contentsOfURL: (NSURL(string: "file:///var/mobile/Media/DCIM/100APPLE/IMG_0043.JPG"))!)
let image = UIImage(data: imgData!)
Here is the answer in code to the question...
PHPhotoLibrary.shared().performChanges({
let assetChangeRequest = PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: uurl)
let assetPlaceholder = assetChangeRequest!.placeholderForCreatedAsset
let albumChangeRequest = PHAssetCollectionChangeRequest(for: self.assetCollection)
}, completionHandler: nil)

swift UIImagePickerController and extracting EXIF data from existing photos

I need to get location data (coordinates for latitude and longitude) from an image picked from PhotoLibrary using UIImagePickerController. Existing answers proposes using fetchAssetsWithALAssetURLs, but it is deprecated for iOS 8 to 11, so I wonder what's the alternative?
Thanks!
This worked for me. For new iOS versions, use the following lines of code.
var asset: PHAsset?
asset = info[UIImagePickerControllerPHAsset] as? PHAsset
Note that asset = nil if the user did not give permission to access his Photo Library since the PHAsset data is sensitive.
To obtain permission, edit Info.plist accordingly and request for permission using PHPhotoLibrary.requestAuthorization().
If you are only supporting iOS 11 and later then you can directly get the PHAsset using the .phAsset key. You only need to use PHAsset fetchAssetsWithALAssetURLs if you need to support iOS 10 or earlier.
Once you have the PHAsset reference, then you can access the location property to get the coordinates of the image.
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
var asset: PHAsset?
if #available(iOS 11.0, *) {
asset = info[.phAsset] as? PHAsset
} else {
if let url = info[.referenceURL] as? URL {
let result = PHAsset.fetchAssets(withALAssetURLs: [url], options: nil)
asset = result.firstObject
}
}
if let asset = asset {
if let location = asset.location {
print("Image location is \(location.coordinate.latitude), \(location.coordinate.longitude)")
}
}
}