gpt4 book ai didi

ios - 如何从图像路径中获取文件名

转载 作者:行者123 更新时间:2023-12-01 18:04:25 27 4
gpt4 key购买 nike

我正在尝试从图像 pathurl 获取文件名
但我收到一个错误,例如“无法将'URL'类型的值转换为强制类型'NSString'”谁能帮我转换为NSstring。提前致谢

if var imgUrl = info[UIImagePickerController.InfoKey.imageURL] as? URL{
let imgName = imgUrl.lastPathComponent
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
let localPath = documentDirectory?.appending(imgName)

var image = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
let data = image.pngData()! as NSData
data.write(toFile: localPath!, atomically: true)
//let imageData = NSData(contentsOfFile: localPath!)!
let photoURL = URL.init(fileURLWithPath: localPath!)//NSURL(fileURLWithPath: localPath!)
print(photoURL)

let filename = (photoURL as NSString).lastPathComponent
// pdfURL is your file url
let fileExtention = (filename as NSString).pathExtension // get your file extension
let pathPrefix = (filename as NSString).deletingPathExtension
img.image = image

最佳答案

(在 Swift 中)所有用于路径操作的方法都在 URL 结构中。无需转换

let filename = photoURL.lastPathComponent
// pdfURL is your file url
let fileExtention = photoURL.pathExtension // get your file extension
let pathPrefix = photoURL.deletingPathExtension.lastPathComponent
img.image = image

并且不要使用 NS Swift 中的类,如果有原生的等价物的话。

请考虑以下警告

Variable 'image' was never mutated; consider changing to 'let' constant

关于ios - 如何从图像路径中获取文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54532016/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com