2017-05-04 256 views
9

用這個看起來沒有關注的簡單問題獲得巨大的賞金。獲取保存到照片相冊的圖像的文件名

在現代的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") } 
} 

有兩個問題:

1. WTH?!?

2.它在賽道條件下失敗。

這是驚人的笨拙,它似乎令人擔憂的方式有很多。

今天真的要走嗎?

+0

你真的需要這個網址嗎?你還可以使用相關的'PHObject'的'localIdentifier'屬性嗎? –

回答

1
extension PHPhotoLibrary { 

    func save(imageData: Data, withLocation location: CLLocation?) -> Promise<PHAsset> { 
     var placeholder: PHObjectPlaceholder! 
     return Promise { fullfil, reject in 
      performChanges({ 
       let request = PHAssetCreationRequest.forAsset() 
       request.addResource(with: .photo, data: imageData, options: .none) 
       request.location = location 
       placeholder = request.placeholderForCreatedAsset 
      }, completionHandler: { (success, error) -> Void in 
       if let error = error { 
        reject(error) 
        return 
       } 

       guard let asset = PHAsset.fetchAssets(withLocalIdentifiers: [placeholder.localIdentifier], options: .none).firstObject else { 
        reject(NSError()) 
        return 
       } 

       fullfil(asset) 
      }) 
     } 
    } 
} 

我認爲你可以PHPhotoLibraryPHObjectPlaceholder做到這一點。

+0

PHPhotoLibrary ...什麼地獄,我什至沒有聽說過這個! – Fattie

+0

https://developer.apple.com/reference/photos/phphotolibrary你可以在這裏找到文檔。 –

+0

對於未來的谷歌,我相信**但我不確定**這是正確的現代答案。 – Fattie

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 *[email protected]"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); 
+0

嗨董,我嘗試發現的路徑***,如果它是在蘋果相冊系統*** – Fattie

+0

@Fattie:我試着用這個代碼模擬器:============= = - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo :(NSDictionary *)info { NSURL * localUrl =(NSURL *)[info valueForKey:UIImagePickerControllerReferenceURL]; NSLog(@「image url%@」,localUrl.absoluteString); } ======,並得到像這樣的東西:image url assets-library://asset/asset.JPG?id = ED7AC36B-A150-4C38-BB8C-B6D696F4F2ED&ext = JPG 告訴我,如果你需要它。 ^^ –

0

也許這是一種不同的方法,但這裏是我在我的應用程序和我做「M滿意吧:

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

相關問題