我正在尝试(和FAILING)让用户上传图像,然后将图像名称和实际图像传递给另一个控制器。在ios11之前,这在模拟器和实际设备上运行良好。但现在,它只能在模拟器上工作,并且每次都会在实际设备上崩溃。我正在使用TestFlight来测试这个,所以我无法看到设备上的错误。但是我看到this并且能够创建我的方法,如下所示:
@objc func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage
if #available(iOS 9.0, *) {
let url = info[UIImagePickerControllerReferenceURL] as! URL
//let assets = PHAsset.fetchAssets(withALAssetURLs: [url], options: nil)
//imageName = PHAssetResource.assetResources(for: assets.firstObject!).first!.originalFilename
let result = PHAsset.fetchAssets(withALAssetURLs: [url], options: nil)
imageName = PHAssetResource.assetResources(for: result.firstObject!).first!.originalFilename
// let asset = result.firstObject
// if(asset == nil){
// print("asset is NIL")
// }else {
// print("asset is not NIL")
// }
// print(asset?.value(forKey: "filename"))
// iconImageName = asset?.value(forKey: "filename") as! String
print("FILENAME START")
print(iconImageName)
print("FILENAME END")
} else {
// Fallback on earlier versions
}
self.dismiss(animated: true, completion: { () -> Void in
})
}
注释掉的代码是我尝试获取文件名的其他方法。为什么这可以在模拟器上工作,但不能在真实设备上工作?我看过网上但这似乎是正确的方式,除非它不是。 PS:很长的故事,但连接到我的Mac时我的设备无法正常工作,这就是我使用TestFlight的原因。
答案 0 :(得分:0)
我相信您可以从信息词典中获取图像路径(并从那里轻松获取文件名):
info[UIImagePickerControllerImageURL]
答案 1 :(得分:0)
您可以通过以下方式轻松地从UIImagePicker
获取fileName:
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)
}
有关详细信息,请参阅以下答案:https://stackoverflow.com/a/40628457/5167909
答案 2 :(得分:-1)
试试这个:
PHAsset *asset = [self assetFromDictionary:info];
if (asset) {
NSData *fileData = nil;
NSString *fileName = [self filenameForAsset:asset];
}
- (PHAsset *)assetFromDictionary:(NSDictionary *)info {
PHAsset *asset = nil;
if (@available(iOS 11.0, *)) {
NSURL *assetURL = info[UIImagePickerControllerImageURL];
if (assetURL) {
asset = [info valueForKey:UIImagePickerControllerPHAsset];
}
} else {
NSURL *assetURL = info[UIImagePickerControllerReferenceURL];
if (assetURL) {
asset = [[PHAsset fetchAssetsWithALAssetURLs:@[assetURL] options:nil] lastObject];
}
}
return asset;
}
- (NSString *)filenameForAsset:(PHAsset *)asset {
NSString *filename = @"";
if (@available(iOS 9.0, *)) {
filename = [[PHAssetResource assetResourcesForAsset:asset] firstObject].originalFilename;
} else {
filename = [asset valueForKey:@"filename"];
}
return filename;
}