Objective-C 如何通过AVURLAsset获取视频创建时间与拍摄位置元数据
代码问题定位
- 核心类型错配:现有代码将
UIImagePickerControllerMediaURL的返回值强转为PHAsset,前者是系统生成的临时文件访问URL,后者是照片库的资源模型类,强转后theAsset属性全为无效值,完全取不到内容。 - 元数据来源认知错误:
AVURLAsset读取的是视频文件容器内封装的元数据,系统从照片库导出临时视频到沙盒tmp目录时,默认不会把照片库层维护的拍摄时间、GPS位置写入视频文件,因此直接读anAsset.creationDate永远返回空值,适配不了视频场景的元数据需求。
正确实现流程
- 元数据统一从对应选中视频的
PHAsset对象获取,和视频文件本身解耦,不需要额外读视频文件的容器信息 - 截取中点帧的逻辑保留原有实现,和元数据提取完全独立
- 原有视频保存到Documents目录的逻辑不需要改动,只需要修正元数据读取的来源即可
关键修正代码片段
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { // 校验选中内容为视频 if (picker.sourceType == UIImagePickerControllerSourceTypePhotoLibrary && [info[UIImagePickerControllerMediaType] isEqualToString:(NSString *)kUTTypeMovie]) { // 正确获取选中视频对应的PHAsset(iOS11+原生支持) PHAsset *selectedVideoAsset = info[UIImagePickerControllerPHAsset]; // 读取拍摄创建时间 NSDate *shootTime = selectedVideoAsset.creationDate; NSDateFormatter *dayFormatter = [[NSDateFormatter alloc] init]; dayFormatter.dateFormat = @"MMMM-dd-yyyy"; dayString = [dayFormatter stringFromDate:shootTime]; NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init]; timeFormatter.dateFormat = @"hh:mm a"; timeString = [timeFormatter stringFromDate:shootTime]; // 读取拍摄位置(部分无权限/无位置的视频可能返回nil) CLLocation *shootLocation = selectedVideoAsset.location; if (shootLocation) { // 存储经纬度供后续标注使用 CLLocationCoordinate2D shootCoord = shootLocation.coordinate; } // 原有临时视频读取、保存文件逻辑保留 NSURL *movieTmpURL = info[UIImagePickerControllerMediaURL]; NSData *movieData = [NSData dataWithContentsOfURL:movieTmpURL]; // 省略原有目录创建、文件写入代码 // ... // 截帧逻辑保持原有实现,AVURLAsset用最终保存的本地文件路径初始化即可 AVURLAsset *frameAsset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:fullPath] options:nil]; if ([frameAsset tracksWithMediaType:AVMediaTypeVideo].count > 0) { AVAssetImageGenerator *imageGenerator = [AVAssetImageGenerator assetImageGeneratorWithAsset:frameAsset]; Float64 durationSeconds = CMTimeGetSeconds(frameAsset.duration); CMTime midpoint = CMTimeMakeWithSeconds(durationSeconds/2.0, 600); NSError *genError; CMTime actualTime; CGImageRef halfWayImage = [imageGenerator copyCGImageAtTime:midpoint actualTime:&actualTime error:&genError]; if (halfWayImage) { myImage.image = [UIImage imageWithCGImage:halfWayImage scale:1.0 orientation:UIImageOrientationRight]; CGImageRelease(halfWayImage); } } } }
补充说明
- 如果需要兼容iOS11以下版本,无法直接通过info字典获取
UIImagePickerControllerPHAsset,可以通过获取照片库的FetchResult匹配临时URL对应的PHAsset,但这类老系统版本目前占比极低,不建议额外做兼容处理增加复杂度。 - 不要依赖视频文件容器内的元数据作为拍摄时间、位置的来源,部分系统导出的视频会剥离这类信息,直接从照片库的PHAsset读取是准确率最高、逻辑最稳定的方案。
内容的提问来源于stack exchange,提问作者user1114881
相关产品推荐
相关产品推荐

