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

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)

Related

Get video in Phpicker in swiftui, but can't play by Videoplayer

I'm trying to load a video from Phpicker and preview it by Video player, but I don't know why it doesn't work.
So I did some research, and most of the solutions put videos in the project file and use Bundle.main.url(forResource:, withExtension:) to play video.
Here's my picker to pick a video. I'm trying to get the video file URL and make a copy using FileManager.default.copyItem(at:, to:) then use URL in Avplayer.
(Pick a video from the photo library)
DispatchQueue.main.async {
guard let videoURL = videoURL as? URL else { return }
debugPrint("video url: \(videoURL.absoluteString)")
let fileID = UUID().uuidString
let fileName = "\(fileID).mp4"
debugPrint("file name: \(fileName)")
let newURL = URL(fileURLWithPath: NSTemporaryDirectory() + fileName)
debugPrint("new url: \(newURL.absoluteString)")
try? FileManager.default.copyItem(at: videoURL, to: newURL)
self.parent.video = newURL
}
(User new URL to play video)
if let url = providerRoomSummitViewModel.roomIntroVideoURL {
VStack {
VideoPlayer(player: AVPlayer(url: URL))
}
}

Get Filename From PHAsset swift 5 IOS13

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

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.

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.

Swift get NSData of a video from photos library

Im using UIImagePickerController to select a video from my library. I need to extract the NSData of my video file. Im using the following operation to select a video from my library but my data appears to be nil however my AVPlayer plays the video from the resulting NSURL so I know problem is not with the NSURL. How can I extract the NSData of my selected video file?
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let fileURL = info[UIImagePickerControllerReferenceURL] as! NSURL!
let data = NSData(contentsOfURL: fileURL)
print(data)
player = AVPlayer(URL: fileURL)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = CGRectMake(0, 0, 300, 300)
self.view.layer.addSublayer(playerLayer)
player.play()
self.dismissViewControllerAnimated(true, completion: nil)
}
Try changing UIImagePickerControllerReferenceURL to
UIImagePickerControllerMediaURL
Instead of let data = NSData(contentsOfURL: fileURL)
let video3 = try NSData(contentsOfURL: videoDataURL, options:
.DataReadingMappedIfSafe)