Save generated GIF to camera roll?
I found the issue was that I was unable to actually grab the GIF from the file. I switched from using CGImageDestinationCreateWithURL
to CGImageDestinationCreateWithData
and used a CFMutableDataRef
to hold the Gif data. I don't know why, but that made saving to camera roll with writeImageDataToSavedPhotosAlbum
work.
How to save gif added image to camera roll?
I solved my problem taking 25 screenshots of gif added imageview using Timer. I added these 25 screenshots to UIImage array and convert it to them video, finally saved to the photo library as a video.
class MainViewController: UIViewController {
private var gifImages: [UIImage] = []
private var gifTimer: Timer?
UIBarButtonItem(barButtonSystemItem: .save,
target: self,
action: #selector(fireTimer))
@objc func fireTimer() {
scheduledTimerWithTimeInterval()
}
private func scheduledTimerWithTimeInterval(){
gifTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(saveEmojiAddedImage), userInfo: nil, repeats: true)
}
//MARK: - SaveEmojiAddedImage
//Final Image
@objc private func saveEmojiAddedImage() {
UIGraphicsBeginImageContextWithOptions(parentView.frame.size, true, 0.0)
parentView.drawHierarchy(in: parentView.bounds, afterScreenUpdates: true) guard let image = UIGraphicsGetImageFromCurrentImageContext() else { return }
UIGraphicsEndImageContext()
if isGIFAdded {
self.gifImages.append(image)
indicator.startAnimating()
view.isUserInteractionEnabled = false
print("Gif Images Count: \(gifImages.count)")
if gifImages.count == 25 {
self.stopTimer()
indicator.stopAnimating()
view.isUserInteractionEnabled = true
}
}
}
func stopTimer() {
if gifTimer != nil {
gifTimer!.invalidate()
gifTimer = nil
DispatchQueue.global(qos: .background).async {
DispatchQueue.main.async {
self.createVideo()
}
}
}
}
Create video using 25 screenshots of imageview
func createVideo() {
let settings = CXEImagesToVideo.videoSettings(codec: AVVideoCodecType.h264.rawValue, width: (gifImages[0].cgImage?.width)!, height: (gifImages[0].cgImage?.height)!)
let movieMaker = CXEImagesToVideo(videoSettings: settings)
movieMaker.createMovieFrom(images: gifImages){ (fileURL:URL) in
if self.isSaveVideo {
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: fileURL)
}) { saved, error in
self.gifImages.removeAll()
if saved {
self.gifImages.removeAll()
DispatchQueue.main.async {
self.presentAlert(withTitle: "Successful", message: "GIF saved successfully")
}
} else {
DispatchQueue.main.async {
self.presentAlert(withTitle: "Error", message: "")
}
}
}
} else {
self.gifImages.removeAll()
self.videoFileURL = fileURL
}
}
}
}
Saving gif file created from screenshots to camera roll
Sadly this can't be solved. The reason for this is that Photos app can't (at the present) display animated GIFs and it only displays one frame from the GIF as a static image. That doesn't mean though that the gif wasn't saved properly. I haven't tried your code but everything seems Ok.
There's a way of testing this. In Messages app (for example) GIFs are being played correctly, so if you share the GIF image from Photos app via ActivityController, select Message and then send it to yourself, you should see animated GIF image in Messages app.
How to write animated GIF to iOS camera roll?
Create an ALAssetLibrary
instance. Use this method with your NSData
: writeImageDataToSavedPhotosAlbum:metadata:completionBlock:
Reference
Saving an animated gif from AppData to photo album - iOS 11
add frameworks foundation and photos
#import <Foundation/Foundation.h>
#import <Photos/Photos.h>
int saveGifToGallery(const char *path0){
NSString *path = [NSString stringWithUTF8String:path0];
NSData *data = [NSData dataWithContentsOfFile:path];
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
PHAssetResourceCreationOptions *options = [[PHAssetResourceCreationOptions alloc] init];
[[PHAssetCreationRequest creationRequestForAsset] addResourceWithType:PHAssetResourceTypePhoto data:data options:options];
} completionHandler:^(BOOL success, NSError * _Nullable error) {
NSLog(@":%d",success);
}];
return 1;
}
Related Topics
How to Add Pagecontrol Inside Uicollectionview Image Scrolling
How to Determine the Current Iphone/Device Model
Adjust Uilabel Height Depending on the Text
How to Use Nsjsonserialization
Objective-C Arc: Strong VS Retain and Weak VS Assign
Importing Commoncrypto in a Swift Framework
Load Resources from Relative Path Using Local HTML in Uiwebview
How to Record a Conversation/Phone Call on Ios
Open Facebook Page in Native Facebook iOS App Via Simple Url Sheme Issue
Test iOS App on Device Without Apple Developer Program or Jailbreak
How to Apply a Perspective Transform to a Uiview
Bold & Non-Bold Text in a Single Uilabel
How to Check If a String Contains Another String in Objective-C