通过UIImagepickerController从摄像头中拾取图片并保存到iOS相册中后,获取图片名称可以通过以下步骤实现:
以下是一个示例代码:
import UIKit
import Photos
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
let imagePicker = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
imagePicker.delegate = self
imagePicker.sourceType = .camera
}
@IBAction func pickImageFromCamera(_ sender: UIButton) {
present(imagePicker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let pickedImage = info[.originalImage] as? UIImage {
UIImageWriteToSavedPhotosAlbum(pickedImage, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
}
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
@objc func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
if let error = error {
print("保存图片到相册失败:\(error.localizedDescription)")
} else {
// 获取保存到相册中的图片名称
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
let fetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions)
if let asset = fetchResult.firstObject {
let assetResources = PHAssetResource.assetResources(for: asset)
if let filename = assetResources.first?.originalFilename {
print("保存到相册的图片名称:\(filename)")
}
}
}
}
}
在上述示例代码中,通过UIImagepickerController从摄像头中获取图片,并将其保存到相册中。然后,在保存图片的回调方法中,使用PHAsset和PHAssetCollection类获取保存到相册中的图片名称。
请注意,这只是一个简单的示例,实际应用中可能需要处理更多的错误情况和逻辑。另外,获取图片名称的方法可能因iOS版本而异,需要根据实际情况进行调整。
推荐的腾讯云相关产品:腾讯云对象存储(COS),用于存储和管理图片等文件资源。产品介绍链接地址:https://cloud.tencent.com/product/cos
领取专属 10元无门槛券
手把手带您无忧上云