通过这个看似简单的问题获得巨额赏金,但没有引起注意。
在现代iOS(2017)中,
这里实际上是我知道将图像保存到iOS照片系统的唯一方法,并获取文件名/路径。
import UIKit
import Photos
func saveTheImage... () {
UIImageWriteToSavedPhotosAlbum(yourUIImage, self,
#selector(Images.image(_:didFinishSavingWithError:contextInfo:)),
nil)
}
func image(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafeRawPointer) {
guard error == nil else {
print("Couldn't save the image!")
return
}
doGetFileName()
}
func doGetFileName() {
let fo: PHFetchOptions = PHFetchOptions()
fo.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
let r = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: fo)
if let mostRecentThingy = r.firstObject {
PHImageManager.default().requestImageData(
for: mostRecentThingy,
options: PHImageRequestOptions(),
resultHandler: { (imagedata, dataUTI, orientation, info) in
if info!.keys.contains("PHImageFileURLKey") {
let path = info!["PHImageFileURLKey"] as! NSURL
print("Holy cow. The path is \(path)")
}
else { print("bizarre problem") }
})
}
else { print("unimaginable catastrophe") }
}
这有两个问题:
这非常笨拙,而且在很多方面看起来很麻烦。
今天真的要走了吗?
答案 0 :(得分:2)
您刚刚以编程方式保存图像,因此您可以从相机获取图像并将其保存为您的路径:
//save image in Document Derectory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSLog(@"Get Path : %@",documentsDirectory);
//create Folder if Not Exist
NSError *error = nil;
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"/YourFolder"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder
NSString *yourPhotoName=@"YourPhotoName";
NSString* path= [dataPath stringByAppendingString:[NSString stringWithFormat:@"/%@.png",yourPhotoName]];
NSData* imageData = UIImagePNGRepresentation(imageToSaved); //which got from camera
[imageData writeToFile:path atomically:YES];
imagePath = path;
NSLog(@"Save Image Path : %@",imagePath);
答案 1 :(得分:0)
也许这是一种不同的方法,但这就是我在我的应用程序中所做的事情,我对此感到满意:
func saveImage(image: UIImage, name: String) {
var metadata = [AnyHashable : Any]()
let iptcKey = kCGImagePropertyIPTCDictionary as String
var iptcMetadata = [AnyHashable : Any]()
iptcMetadata[kCGImagePropertyIPTCObjectName as String] = name
metadata[iptcKey] = iptcMetadata
let library = ALAssetsLibrary()
library.writeImage(toSavedPhotosAlbum: image.cgImage, metadata: metadata) { url, error in
// etc...
}
}
如果您不想使用ALAssetsLibrary,您可能会对this answer感兴趣。