如何在 swift 中刷新照片库?

How to refresh photo gallery in swift?

如何刷新 swift 中的照片库?如果我拍照,我必须关闭应用程序然后重新启动它才能看到它。我想自动刷新画廊。解决此问题的最佳方法是什么?

这取决于您如何实现该功能。

1) 如果使用Tableview/ColloectionView,

拍照后Option点击Use打开CameraViewController.You必须实现UIImagePickerControllerDelegate,UINavigationControllerDelegate.Delegate方法:

    - (void)imagePickerController:(UIImagePickerController *)picker
    didFinishPickingMediaWithInfo:(NSDictionary *)info
   {
          //Made your code according your requirements.
         //Reload TableView/ColloectionView..
   }

2) 如果只在UIImageView中展示,

- (void)imagePickerController:(UIImagePickerController *)picker
    didFinishPickingMediaWithInfo:(NSDictionary *)info
   {
          //Made your code according your requirements.
          [picker dismissModalViewControllerAnimated:YES];
    UIImage* image = [info objectForKey:UIImagePickerControllerOriginalImage];
    UIImage *yourImageView = image;
    //show image in your imageview..
   }

将此添加到您的 viewDidLoad 方法中:
NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(ViewController.refreshView), userInfo: nil, repeats: true) 并在 refreshView 中实现您想要执行的操作。

更好的方法: 使用 observer pattern!

经过一些调查后我发现,每当您从设备的相机拍照时,您的应用程序都会进入后台,然后您会将您的应用程序带到前台。所以,在我看来,你必须在 AppDelegate 中保留一个 tableView/CollectionView(取决于你的实现)的实例。 将您的 tableView/CollectionView 重新加载为

func applicationWillEnterForeground(application: UIApplication) { self.yourTableView.reloadData() }

在您的 AppDelegate.swift applicationWillEnterForeground 函数中。我想这会解决你的问题。

或者, 只需创建一个 delegate 并在 AppDelegate.swift applicationWillEnterForeground 函数中调用它,然后实现在 ViewController 中委托函数并重新加载 tableView 或 collectionView。 这两种解决方案都对我有用。我想它也适合你。

如果您正在使用 PHPhotoLibrary This Link 可能对您非常有帮助。你只需要注册一个变化观察者并开始观察,在上面的link中解释得很好。