如何使用资产库在uiimagepickercontroller中获取文件名?

时间:2016-11-16 09:06:04

标签: ios iphone swift uiimagepickercontroller

我想从UIImagepickercontroller获取文件名。我不想使用ALAssetLibrary,因为它在iOS 9中已经取消了。请告诉我如何使用它。我使用了下面的代码,但是它返回了我的图像名称<{1}}始终为每个文件。

Asset.jpg

16 个答案:

答案 0 :(得分:16)

我建议您使用Photos框架获取图片的名称,下面是获取所选图片名称的代码

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let imageURL = info[UIImagePickerControllerReferenceURL] as? URL {
        let result = PHAsset.fetchAssets(withALAssetURLs: [imageURL], options: nil)
        let asset = result.firstObject
        print(asset?.value(forKey: "filename"))

    }

    dismiss(animated: true, completion: nil)
}

答案 1 :(得分:6)

在iOS 11之前

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let imageURL = info[UIImagePickerControllerReferenceURL] as? URL {
        let result = PHAsset.fetchAssets(withALAssetURLs: [imageURL], options: nil)
        let assetResources = PHAssetResource.assetResources(for: result.firstObject!)

        print(assetResources.first!.originalFilename)
    }

    dismiss(animated: true, completion: nil)
}

iOS 11之后

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let asset = info[UIImagePickerControllerPHAsset] as? PHAsset {
        let assetResources = PHAssetResource.assetResources(for: asset)

        print(assetResources.first!.originalFilename)
    }

    dismiss(animated: true, completion: nil)
}

答案 2 :(得分:5)

2018年5月6日更新

强制解包的选项有时会返回nil,我认为这是因为用户使用相机来捕获新图像而不是从照片库中选择一个。当我看到nil时,我更新了代码以返回生成的名称。

原始回答

这对我有用,而不必依赖filename键(请原谅强行解包选项:))

extension MyViewController : UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        guard let image = info[UIImagePickerControllerEditedImage] as? UIImage else {
            DDLogDebug("No image chosen")
            return
        }

        if let url = info[UIImagePickerControllerReferenceURL] as? URL {
            let assets = PHAsset.fetchAssets(withALAssetURLs: [url], options: nil)
            if let firstAsset = assets.firstObject,
            let firstResource = PHAssetResource.assetResources(for: firstAsset).first {
                fileName = firstResource.originalFilename
            } else {
                fileName = generateNameForImage()
            }
        } else {
            fileName = generateNameForImage()
        }

        DDLogDebug("File name = \(fileName)")

        dismiss(animated: true)
    }

    func generateNameForImage() -> String {
        return "IMG_random_string"
    }

}

答案 3 :(得分:3)

Swift 5,iOS 11 +

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    let photo = info[.phAsset] as? PHAsset
    let filename = photo?.value(forKey: "filename") as! String
}

答案 4 :(得分:2)

您可以尝试使用iOS 11

 func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let asset = info[UIImagePickerControllerPHAsset] as? PHAsset {
        if let fileName = (asset.value(forKey: "filename")) as? String {
            //Do your stuff here
        }
    }

    picker.dismiss(animated: true, completion: nil)
}

确保将此NSPhotoLibraryUsageDescription添加到Infor.plist

答案 5 :(得分:1)

按照以下步骤操作。

我相信它会对你有帮助。

这里我们将所选图像保存到文档目录中,然后尝试从文档目录中访问这些图像。

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
    let imageURL = info[UIImagePickerControllerReferenceURL] as NSURL
    let imageName = imageURL.path!.lastPathComponent
    let documentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as String
    let localPath = documentDirectory.stringByAppendingPathComponent(imageName)
    let image = info[UIImagePickerControllerOriginalImage] as UIImage
    let data = UIImagePNGRepresentation(image)
    data.writeToFile(localPath, atomically: true)
    let imageData = NSData(contentsOfFile: localPath)!
    let photoURL = NSURL(fileURLWithPath: localPath)
    let imageWithData = UIImage(data: imageData)!
    picker.dismissViewControllerAnimated(true, completion: nil)
}

答案 6 :(得分:1)

导入照片

func getFileName(info: [String : Any]) -> String {

    if let imageURL = info[UIImagePickerControllerReferenceURL] as? URL {
        let result = PHAsset.fetchAssets(withALAssetURLs: [imageURL], options: nil)
        let asset = result.firstObject
        let fileName = asset?.value(forKey: "filename")
        let fileUrl = URL(string: fileName as! String)
        if let name = fileUrl?.deletingPathExtension().lastPathComponent {
        print(name)
        return name
        }
    }
    return ""

}

在方法中调用它&#34; didFinishPickingMediaWithInfo&#34;像这样:

let fileName = getFileName(info: info)

答案 7 :(得分:1)

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    let selectedFileName = ""
    if #available(iOS 11.0, *) {
        if let imageUrl = info[.imageURL] as? URL {
            selectedFileName = imageUrl.lastPathComponent
        }
    } else {
        if let imageURL = info[.referenceURL] as? URL {
            let result = PHAsset.fetchAssets(withALAssetURLs: [imageURL], options: nil)
            if let firstObject = result.firstObject {
                let assetResources = PHAssetResource.assetResources(for: firstObject)
                selectedFileName = assetResources.first?.originalFilename
            }
        }
    }

    picker.dismiss(animated: true, completion: nil)
}

答案 8 :(得分:1)

在寻找一种从UIImagePickerController检索文件名的方法时,我遇到了这个问题。

我尝试了答案中提到的所有方法,但结果不一致。

作为我自己的iOS新手开发人员,我不会尝试详述这些方式之间的机制。相反,我将演示我的发现。

注意:全部在iOS 13下使用Swift 5。

第一种方法,我认为它不是真正的文件名,因为它一直在变化。我猜这是本地路径名,因为图像选择器会将图像保存到应用程序的临时目录中。

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
  guard let url = info[.imageURL] as? NSURL else { return }
  let filename = url.lastPathComponent!
  print(filename) // 46484E68-94E8-47B7-B0F4-E52EA7E480A9.jpeg
}

第二种方式,每次我选择它时都是合理的。我认为它可以用作文件名,但并非完美无缺。

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
  let photo = info[.phAsset] as? PHAsset
  var filename = photo?.value(forKey: "filename") as? String ?? ""
  print(filename) // IMG_0228.JPG
}

第三种方法为您获取原始文件名,即您在Mac中看到的文件名。假设您将AirDrop一张名为“ Apple.jpg”的照片拖放到手机上,只有这样,您才能获得名称为“ Apple.jpg”的照片

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
  let photo = info[.phAsset] as? PHAsset
  let res = PHAssetResource.assetResources(for: photo!)
  let filename = res[0].originalFilename
  print(filename) // Apple.jpg
}

答案 9 :(得分:0)

  func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { 

         if let asset = PHAsset.fetchAssets(withALAssetURLs: [info[UIImagePickerControllerReferenceURL] as! URL],options: nil).firstObject {              

            var resources = PHAssetResource.assetResources(for: asset)

            let orgFilename: String = ((resources[0] as? PHAssetResource)?.originalFilename)!

            print("filename:",orgFilename)
     }
    }

答案 10 :(得分:0)

对我来说,它运行完美,

if let imgUrl = info[UIImagePickerControllerImageURL] as? URL{
   let imgName = imgUrl.lastPathComponent
   print(imgName)
   let imgExtension = imgUrl.pathExtension
   print(imgExtension)
}

答案 11 :(得分:0)

这是我快速完成4的方法

if let url = info[UIImagePickerController.InfoKey.imageURL] as? URL {
        fileName = url.lastPathComponent
        fileType = url.pathExtension
    }

答案 12 :(得分:0)

    let fileName = (info[.imageURL] as? URL)?.lastPathComponent

答案 13 :(得分:0)

我想要图像的名称并尝试了它,这对我有用,希望它也对您有用,您可以在需要PHPhotoLibrary权限之前使用uiimagepickercontroller中的phAsset对象 注意:-在此之前....... **导入照片**

PHPhotoLibrary.requestAuthorization { (status) in
        switch status {
            
        case .notDetermined:
            break
        case .restricted:
            break
        case .denied:
            break
        case .authorized:
            if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {                      
                    let imagePickerController = UIImagePickerController()
                    imagePickerController.delegate = self;
                    imagePickerController.sourceType = .photoLibrary
                    
                    let cancelButtonAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
                    UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes , for: .normal)
                    
                    imagePickerController.modalPresentationStyle = .fullScreen
                    self.present(imagePickerController, animated: true, completion: nil)
                    
                }
            }
        @unknown default:
            fatalError()
        }
    }

实现uiimagepicker的委托方法,并在didFinishPickingMediaWithInfo内部添加以下内容:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    
    if (info[UIImagePickerController.InfoKey.originalImage] as? UIImage) != nil {

      if let photoObj = (info[UIImagePickerController.InfoKey.phAsset] as? PHAsset) {
          let photoName = pHObjc.localIdentifier 
    // returns local photo id which will be unique for each photo
     }
   }
}

答案 14 :(得分:0)

此代码对我有用(Swift 5):

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    if let imgUrl = info[UIImagePickerController.InfoKey.imageURL] as? URL{
        let imgName = imgUrl.lastPathComponent
        let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
        let localPath = documentDirectory?.appending(imgName)

        let image = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
        let data = image.pngData()! as NSData
        data.write(toFile: localPath!, atomically: true)
        let photoURL = URL.init(fileURLWithPath: localPath!)
        let filename = photoURL.lastPathComponent
        print(filename)
       }
    picker.dismiss(animated: true, completion: nil)
}

答案 15 :(得分:0)

适用于 iOS 11 及更高版本

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        // get imageURL and asset
        if let asset = info[UIImagePickerController.InfoKey.phAsset] as? PHAsset, let imageURL = info[UIImagePickerController.InfoKey.imageURL] as? URL{
            // got asset and imageURL
        } else {
            // show error
        }
        dismiss(animated: true, completion: nil)
    }