简体   繁体   中英

How to refresh photo gallery in swift?

How can I refresh the photo gallery in swift? If I take a picture I have to close the app and then restart it to see it. I want to refresh the gallery automatically. What's the best way to solve this problem?

It depends on how you implement that functionality.

1) If you use Tableview/ColloectionView,

After taking picture Option click Use in opened CameraViewController.You have to implement UIImagePickerControllerDelegate, UINavigationControllerDelegate.Delegate method :

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

2) If you show in just 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..
   }

Add this to your viewDidLoad method:
NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(ViewController.refreshView), userInfo: nil, repeats: true) and implement in the refreshView what you want to do.

Better method: use an observer pattern !

After few investigation I found that, whenever You are taking a picture from device's camera your app will go in background and then you will bring your app to foreground. So, in my opinion you have to keep an instance of the tableView/CollectionView(depends upon your implementation) in AppDelegate. Reload your tableView/CollectionView as

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

in your AppDelegate.swift applicationWillEnterForeground function. I think this will solve your problem.

Or, Simply make a delegate and call it in your AppDelegate.swift applicationWillEnterForeground function, and implement the delegate function in your ViewController and reload the tableView or collectionView. Both solutions are working for me. I think it will also work for you.

If you are using PHPhotoLibrary This Link might be extremely helpful for you. You just need to register a change observer and start observing, it's very well explained in the link above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM