Reputation: 822
I have a gif image url and want to download it to the documents directory, for this I have tried using
if let gifImageData = UIImagePNGRepresentation(image!) {
try gifImageData.write(to: fileURL, options: .atomic)
}
and also
if let jpegImageData = UIImageJPEGRepresentation(image!, 1.0) {
try jpegImageData.write(to: fileURL, options: .atomic)
}
But this image is saving as a single png/jpg image and not as animated gif
Any solution for this?
Upvotes: 2
Views: 1029
Reputation: 6067
check you should download
func download() {
DispatchQueue.global(qos: .background).async {
if let url = URL(string: "https://upload.wikimedia.org/wikipedia/commons/2/2c/Rotating_earth_%28large%29.gif"),
let urlData = NSData(contentsOf: url)
{
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0];
let filePath="\(documentsPath)/tempFile.gif";
DispatchQueue.main.async {
urlData.write(toFile: filePath, atomically: true)
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: URL(fileURLWithPath: filePath))
}) { completed, error in
if completed {
print("photo is saved!")
}
}
}
}
}
}
Upvotes: 0
Reputation: 5005
Problem is with you filename, Try this:
//The URL to Save
let yourURL = NSURL(string: "http://somewebsite.com/somefile.gif")
//Create a URL request
let urlRequest = NSURLRequest(URL: yourURL!)
//get the data
let theData = NSURLConnection.sendSynchronousRequest(urlRequest, returningResponse: nil, error: nil)
//Get the local docs directory and append your local filename.
var docURL = (NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)).last as? NSURL
docURL = docURL?.URLByAppendingPathComponent( "myFileName.gif")
//Lastly, write your file to the disk.
theData?.writeToURL(docURL!, atomically: true)
Upvotes: 1