How to show images within folder using collection view in swift - ios

I am working on UICollectionView fetching gallery images and shown in UICollectionViewCell but i need to shown all images within one single folder.
Is there any solution for this?

You can try this way.Below code is fetch the "Repost" folder from gallery and fetch all the photos of it.
func getImages() {
image = []
let albumName = "Repost" //album name
let fetchOptions = PHFetchOptions()
var assetCollection = PHAssetCollection()
fetchOptions.predicate = NSPredicate(format: "title = %#", albumName)
let collection:PHFetchResult = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)
if let _:AnyObject = collection.firstObject{
//found the album
assetCollection = collection.firstObject!
albumFound = true
}
else { albumFound = false
print("album not found")
}
let assets = PHAsset.fetchAssets(in: assetCollection, options: nil) as! PHFetchResult<AnyObject>
assets.enumerateObjects({ (object, count, stop) in
// self.cameraAssets.add(object)
if object.mediaType == .image
{
self.image.append(object as! PHAsset) // for image
}
})
self.image.reverse()
self.imgcollection.reloadData()
}
Don't forgot to import photos framework.
Thanks.

In case you are still struggling to figure out here is the code snippet, good luck
func saveImageToDocumentDirectory(image: UIImage ) {
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let fileName = "image001.png" // name of the image to be saved
let fileURL = documentsDirectory.appendingPathComponent(fileName)
if let data = UIImageJPEGRepresentation(image, 1.0),!FileManager.default.fileExists(atPath: fileURL.path) {
do {
try data.write(to: fileURL)
print("file saved")
} catch {
print("error saving file:", error)
}
}
}
func loadImageFromDocumentDirectory(nameOfImage : String) -> UIImage {
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
if let dirPath = paths.first {
let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(nameOfImage)
let image = UIImage(contentsOfFile: imageURL.path)
return image!
}
return UIImage.init(named: "default.png")!
}

Related

How to fetch all albums with images from iPhone without taking time in Swift?

I tried to fetch all images from album. It fetches all images with their URL's and image data, but it does not fetch images directly from given URL path, So I need to download images in Document Directory and then get path. So it's taking too much time. I use below code. I want fetch images like iPhone photos library fetches.
Please find error.
func fatchImagesfromAlbum() {
DispatchQueue.global(qos: .background).async {
self.photoAssets = self.fetchResult as! PHFetchResult<AnyObject>
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.image.rawValue)
self.photoAssets = PHAsset.fetchAssets(in: self.assetCollection, options: fetchOptions) as! PHFetchResult<AnyObject>
for i in 0..<self.photoAssets.count{
autoreleasepool {
let asset = self.photoAssets.object(at: i)
let imageSize = CGSize(width: asset.pixelWidth,
height: asset.pixelHeight)
let options = PHImageRequestOptions()
options.deliveryMode = .fastFormat
options.isSynchronous = true
options.isNetworkAccessAllowed = true
self.imageManager.requestImage(for: asset as! PHAsset, targetSize: imageSize, contentMode: .aspectFill, options: options, resultHandler: { (image, info) -> Void in
if image != nil {
let image1 = image as! UIImage
let imageUrl = info!["PHImageFileURLKey"] as? NSURL
let imageName = imageUrl?.lastPathComponent
let urlString: String = imageUrl!.path!
let theFileName = (urlString as NSString).lastPathComponent
self.imageName.append("\(theFileName)")
self.imagePath.append("\(urlString)")
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let photoURL = NSURL(fileURLWithPath: documentDirectory)
let localPath = photoURL.appendingPathComponent(imageName!)
DispatchQueue.global(qos: .background).async {
if !FileManager.default.fileExists(atPath: localPath!.path) {
do {
try UIImageJPEGRepresentation(image1, 0.1)?.write(to: localPath!)
print("file saved")
}catch {
print("error saving file")
}
}
else {
print("file already exists")
}
}
}
})
DispatchQueue.main.async
{
self.collectionView.reloadData()
}
}
}
self.hudHide()
}
PHPhotoLibrary.shared().register(self)
if fetchResult == nil {
let allPhotosOptions = PHFetchOptions()
allPhotosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
fetchResult = PHAsset.fetchAssets(with: allPhotosOptions)
}
}
I recommend simply using UIImagePickerController or if your app requires multiple image selection functionality, a third-party library like DKImagePickerController. As another user already mentioned in the comments, these will only copy the image(s) the user selected into your app's directory and save on processing time.

Swift 3 adding an Image to Documents and Retrieving

I feel like I am missing something major as I don't receive any errors or null values, but anytime I try to retrieve my image it returns "" because it doesn't exist?
This is how I am passing the image data:
URLSession.shared.dataTask(with: url! as URL, completionHandler:{ (data, response, error) in
//if download error
if error != nil{
print(error!)
return
}
guard let imageData = UIImage(data: data!) else { return }
DispatchQueue.main.async{
self.imgPortrait.image = imageData
ImagePortrait().saveImageDocumentDirectory(image: imageData)
}
The data is displayed on imgPortrait completely fine. Here are the rest of the functions where: /\(userUID)/\(CharacterSelection.sharedInstance.getActiveCharacterName()) is optional. When it goes to retrieve the image and when it saves it I can confirm the paths are exactly the same. I feel like it's how I am saving the image with createFile, but I am unsure.
func saveImageDocumentDirectory(image: UIImage){
if let userUID = Auth.auth().currentUser?.uid{
let fileManager = FileManager.default
let paths = (getDirectoryPath() as NSString).appendingPathComponent("/\(userUID)/\(CharacterSelection.sharedInstance.getActiveCharacterName())/characterPortrait.png")
createDirectory(name: (getDirectoryPath() as NSString) as String)
let imageData = UIImagePNGRepresentation(image)
fileManager.createFile(atPath: paths as String, contents: imageData, attributes: nil)
}
}
func getDirectoryPath() -> String {
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = paths[0]
return documentsDirectory
}
func getImage() -> String{
if let userUID = Auth.auth().currentUser?.uid{
let fileManager = FileManager.default
let imagePath = (self.getDirectoryPath() as NSString).appendingPathComponent("/\(userUID)/\(CharacterSelection.sharedInstance.getActiveCharacterName())/characterPortrait.png")
if fileManager.fileExists(atPath: imagePath){
return imagePath
}else{
print("No Image")
return ""
}
}
else{
return ""
}
}
func createDirectory(name: String){
let fileManager = FileManager.default
let paths = (getDirectoryPath() as NSString).appendingPathComponent(name)
if !fileManager.fileExists(atPath: paths){
try! fileManager.createDirectory(atPath: paths, withIntermediateDirectories: true, attributes: nil)
}else{
print("Directory is already created.")
}
}
Thanks in advance!
Well after a few hours I figured it out. Looks like the directory wasn't being created. Solved it by:
func saveImageDocumentDirectory(image: UIImage){
if let userUID = Auth.auth().currentUser?.uid{
let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent("\(userUID)_\(CharacterSelection.sharedInstance.getActiveCharacterName())_characterPortrait.png")
do {
try UIImagePNGRepresentation(image)?.write(to: fileURL, options: .atomic)
} catch {
print(error)
}
}
}
func getImage() -> UIImage{
if let userUID = Auth.auth().currentUser?.uid{
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
if let dirPath = paths.first
{
let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("\(userUID)_\(CharacterSelection.sharedInstance.getActiveCharacterName())_characterPortrait.png")
if let image = UIImage(contentsOfFile: imageURL.path){
return image
}
else{
print("Image isn't found.")
return UIImage(named: "default_portrait.png")!
}
}
else{
print("Image isn't found.")
return UIImage(named: "default_portrait.png")!
}
}
else{
print("Image isn't found.")
return UIImage(named: "default_portrait.png")!
}
}

Saving an Asset List (array) to specific CKRecord

I've a CKRecord type created in the CloudKit backend with some properties related to that class.
I've String properties, Bytes and I have a Asset List property, so store some images (multiple images related to a single record).
Now I'm trying so store some images and then fill the property and then trying to save it to CloudKit, but it's not working.
Code goes as it follows:
var images_array = [CKAsset]()
// append the an image to the array
images_array.append(CKAsset(fileURL: writeImage(image: selectedImage) as URL))
let record = CKRecord(recordType: recordName)
record["class_title"] = someString as CKRecordValue
record["class_body"] = someString as CKRecordValue
record["images_array"] = images_array as CKRecordValue
saveRecord(record)
func saveRecord(_ xrecord: CKRecord) {
let publicData = CKContainer.default().publicCloudDatabase
let record: [CKRecord] = [xrecord]
let saveOperation = CKModifyRecordsOperation.init(recordsToSave: record, recordIDsToDelete: nil)
saveOperation.perRecordCompletionBlock = {(record, error) -> Void in
if (error != nil) {
print("error")
}
}
publicData.add(saveOperation)
}
func writeImage(image: UIImage) -> URL {
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let fileURL = NSURL(fileURLWithPath: documentsURL.absoluteString).appendingPathComponent(".jpg")
if let imageData = image.lowestQualityJPEGNSData {
do {
try imageData.write(to: fileURL!)
} catch {
print("ERRO 001 = \(error.localizedDescription)")
}
}
return fileURL!
}
extension UIImage {
var uncompressedPNGData: Data? { return UIImagePNGRepresentation(self) }
var highestQualityJPEGNSData: Data? { return UIImageJPEGRepresentation(self, 1.0) }
var highQualityJPEGNSData: Data? { return UIImageJPEGRepresentation(self, 0.75) }
var mediumQualityJPEGNSData: Data? { return UIImageJPEGRepresentation(self, 0.5) }
var lowQualityJPEGNSData: Data? { return UIImageJPEGRepresentation(self, 0.25) }
var lowestQualityJPEGNSData:Data? { return UIImageJPEGRepresentation(self, 0.0) }
}
If I only save the strings, everything works perfectly but with images it doesn't save the record.
I know there might be any issue with the appending, or I have to save the array in other way, or I shouldn't save it as CKRecordValue.
Do you have any tip on how to achieve this?
Thanks
When you create your local asset file you should do so with the atomic write option. This will ensure that the file is completely written before CloudKit attempts to upload the asset.
This is the asset file creation function I use in the Seam 3 library:
fileprivate func createAsset(data: Data) -> CKAsset? {
var returnAsset: CKAsset? = nil
let tempStr = ProcessInfo.processInfo.globallyUniqueString
let filename = "\(tempStr)_file.bin"
let baseURL = URL(fileURLWithPath: NSTemporaryDirectory())
let fileURL = baseURL.appendingPathComponent(filename, isDirectory: false)
do {
try data.write(to: fileURL, options: [.atomicWrite])
returnAsset = CKAsset(fileURL: fileURL)
} catch {
print("Error creating asset: \(error)")
}
return returnAsset
}
You have to take Array of CKAsset for images.
var imageUrls = [CKAsset]()
Now get all images using for-loop. And save CKAsset of images.
for images in self.arrayImageSelected{
var myImage = UIImage()
if (images.isKindOfClass(PHAsset)){
let imageC = images as? PHAsset
myImage = self.getAssetThumbnail(imageC!)
}else if (images.isKindOfClass(UIImage)){
myImage = (images as? UIImage)!
}
let imagePath = self.storeImageAtDocumentDirectory(myImage, titleName: self.strTitle)
myPAth.append(imagePath)
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let FbPath = paths.stringByAppendingString("/Custom")
let filePathToWrite = "\(FbPath)" + imagePath
let urls = NSURL(fileURLWithPath: filePathToWrite)
let imageAsset = CKAsset(fileURL: urls)
imageUrls.append(imageAsset)
}
Set Your array.
record.setObject(imageUrls, forKey: "images_array")

how to load image from local path ios swift (by path)

In my app I am storing an image in local storage and I am saving the path of that image in my database. How can I load the image from that path?
Here is the code I am using in order to save the image:
let myimage : UIImage = UIImage(data: data)!
let fileManager = NSFileManager.defaultManager()
let urls = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
let documentDirectory = urls[0] as NSURL
print(documentDirectory)
let currentDate = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .NoStyle
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let convertedDate = dateFormatter.stringFromDate(currentDate)
let imageURL = documentDirectory.URLByAppendingPathComponent(convertedDate)
imageUrlPath = imageURL.absoluteString
print(imageUrlPath)
UIImageJPEGRepresentation(myimage,1.0)!.writeToFile(imageUrlPath, atomically: true)
And this is the path where my image stored
file:///var/mobile/Containers/Data/Application/B2A1EE50-D800-4BB0-B475-6C7F210C913C/Documents/2016-06-01%2021:49:32
This is how i tried to retrieve the image but it's not displaying anything.
let image : String = person?.valueForKey("image_local_path") as! String
print(person!.valueForKey("image_local_path")! as! String)
cell.img_message_music.image = UIImage(contentsOfFile: image)
Folder /B2A1EE50- ... changes every time you run application.
../Application/B2A1EE50-D800-4BB0-B475-6C7F210C913C/Documents/..
Which works for me is to store fileName and get documents folder.
Swift 5
Create getter for directory folder
var documentsUrl: URL {
return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
}
Save image :
private func save(image: UIImage) -> String? {
let fileName = "FileName"
let fileURL = documentsUrl.appendingPathComponent(fileName)
if let imageData = image.jpegData(compressionQuality: 1.0) {
try? imageData.write(to: fileURL, options: .atomic)
return fileName // ----> Save fileName
}
print("Error saving image")
return nil
}
Load image :
private func load(fileName: String) -> UIImage? {
let fileURL = documentsUrl.appendingPathComponent(fileName)
do {
let imageData = try Data(contentsOf: fileURL)
return UIImage(data: imageData)
} catch {
print("Error loading image : \(error)")
}
return nil
}
Also you can try this.
Check if your path exist
if NSFileManager.defaultManager().fileExistsAtPath(imageUrlPath) {}
Create an URL to your path
let url = NSURL(string: imageUrlPath)
Create data to you URL
let data = NSData(contentsOfURL: url!)
Bind the url to your imageView
imageView.image = UIImage(data: data!)
Final code:
if NSFileManager.defaultManager().fileExistsAtPath(imageUrlPath) {
let url = NSURL(string: imageUrlPath)
let data = NSData(contentsOfURL: url!)
imageView.image = UIImage(data: data!)
}
This code works for me
func getImageFromDir(_ imageName: String) -> UIImage? {
if let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let fileURL = documentsUrl.appendingPathComponent(imageName)
do {
let imageData = try Data(contentsOf: fileURL)
return UIImage(data: imageData)
} catch {
print("Not able to load image")
}
}
return nil
}
Swift 4:
if FileManager.default.fileExists(atPath: imageUrlPath) {
let url = NSURL(string: imageUrlPath)
let data = NSData(contentsOf: url! as URL)
chapterImage.image = UIImage(data: data! as Data)
}
Replace absoluteString with path
let myimage : UIImage = UIImage(data: data)!
let fileManager = NSFileManager.defaultManager()
let urls = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
let documentDirectory = urls[0] as NSURL
print(documentDirectory)
let currentDate = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .NoStyle
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let convertedDate = dateFormatter.stringFromDate(currentDate)
let imageURL = documentDirectory.URLByAppendingPathComponent(convertedDate)
imageUrlPath = imageURL.path
print(imageUrlPath)
UIImageJPEGRepresentation(myimage,1.0)!.writeToFile(imageUrlPath, atomically: true)
This sample code may save someone some typing,
write an UIImage to disk in your own directory:
IM = UIImage, your image. for example, IM = someUIView.image or from the camera
let newPhotoFileName = randomNameString() + ".jpeg"
let imagePath = checkedImageDirectoryStringPath() + "/" + newPhotoFileName
let imData = UIImageJPEGRepresentation(IM, 0.20)
FileManager.default.createFile(atPath: imagePath, contents: imData, attributes: nil)
print("saved at filename \(newPhotoFileName)")
later to read that image ...
.. and convert it back to a UIImage as in a UIImageView
NAME = that filename, like jahgfdfs.jpg
let p = checkedImageDirectoryStringPath() + "/" + NAME
devCheckExists(fullPath: p)
var imageData: Data? = nil
do {
let u = URL(fileURLWithPath: p)
imageData = try Data(contentsOf: u)
}
catch {
print("catastrophe loading file?? \(error)")
return
}
// and then to "make that an image again"...
imageData != nil {
picture.image = UIImage(data: imageData!)
print("that seemed to work")
}
else {
print("the imageData is nil?")
}
// or for example...
Alamofire.upload(
multipartFormData: { (multipartFormData) in
multipartFormData.append(imageData!,
withName: "file", fileName: "", mimeType: "image/jpeg")
...
Here are the extremely handy functions used above...
func checkedImageDirectoryStringPath()->String {
// create/check OUR OWN IMAGE DIRECTORY for use of this app.
let paths = NSSearchPathForDirectoriesInDomains(
.documentDirectory, .userDomainMask, true)
if paths.count < 1 {
print("some sort of disaster finding the our Image Directory - giving up")
return "x"
// any return will lead to disaster, so just do that
// (it will then gracefully fail when you "try" to write etc)
}
let docDirPath: String = paths.first!
let ourDirectoryPath = docDirPath.appending("/YourCompanyName")
// so simply makes a directory called "YourCompanyName"
// which will be there for all time, for your use
var ocb: ObjCBool = true
let exists = FileManager.default.fileExists(
atPath: ourDirectoryPath, isDirectory: &ocb)
if !exists {
do {
try FileManager.default.createDirectory(
atPath: ourDirectoryPath,
withIntermediateDirectories: false,
attributes: nil)
print("we did create our Image Directory, for the first time.")
// never need to again
return ourDirectoryPath
}
catch {
print(error.localizedDescription)
print("disaster trying to make our Image Directory?")
return "x"
// any return will lead to disaster, so just do that
}
}
else {
// already exists, as usual.
return ourDirectoryPath
}
}
and
func randomNameString(length: Int = 7)->String{
enum s {
static let c = Array("abcdefghjklmnpqrstuvwxyz12345789".characters)
static let k = UInt32(c.count)
}
var result = [Character](repeating: "a", count: length)
for i in 0..<length {
let r = Int(arc4random_uniform(s.k))
result[i] = s.c[r]
}
return String(result)
}
and
func devCheckExists(fullPath: String) {
var ocb: ObjCBool = false
let itExists = FileManager.default.fileExists(atPath: fullPath, isDirectory: &ocb)
if !itExists {
// alert developer. processes will fail at next step
print("\n\nDOES NOT EXIST\n\(fullPath)\n\n")
}
}
This is working for me and I think is a fast and clean way to do it.
Swift 5.0
let fileManager = NSFileManager.defaultManager()
let urls = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
let documentDirectory = urls[0] as NSURL
print(documentDirectory)
let currentDate = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .NoStyle
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let convertedDate = dateFormatter.stringFromDate(currentDate)
let imageURL = documentDirectory.URLByAppendingPathComponent(convertedDate)
let imageData = try? Data(contentsOf: imageUrl)
let image = UIImage(data: imageData!)
Where "imageUrl" is the value of your imageURL from documents folder. And "image" is the resulting image you can use anywhere you need.
1.cell.image.sd_setShowActivityIndicatorView(true)
2.cell.image.sd_setIndicatorStyle(.gray)
3.cell.image.image = UIImage(contentsOfFile: urlString!)

URL of image after UIImageWriteToSavedPhotosAlbum in Swift

After i took a photo with the camera i save the image with the following code:
UIImageWriteToSavedPhotosAlbum(image, self,"image:didFinishSavingWithError:contextInfo:", nil)
This saves the image in the camera roll. Additionally i want to save the URL to this saved image in Core Data. Is it possible to retrieve the URL (or the Path) to so that i only need to save this URL and not the full image in Core Data?
After reading a lot of answers written in ObjectivC i finally figured out how to write this in Swift with Xcode 6.2:
ALAssetsLibrary().writeImageToSavedPhotosAlbum(image.CGImage, orientation: ALAssetOrientation(rawValue: image.imageOrientation.rawValue)!,
completionBlock:{ (path:NSURL!, error:NSError!) -> Void in
println("\(path)")
})
Here is my combination..
Saving Image :
let imageData = NSData(data:UIImagePNGRepresentation(pickedimage))
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
var docs: String = paths[0] as! String
let fullPath = docs.stringByAppendingPathComponent("yourNameImg.png")
let result = imageData.writeToFile(fullPath, atomically: true)
print(fullPath)
Get Image:
let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
if let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
{
if paths.count > 0
{
if let dirPath = paths[0] as? String
{
let readPath = dirPath.stringByAppendingPathComponent("yourNameImg.png")
let image = UIImage(contentsOfFile: readPath)
UploadImagePreview.image = image
}
}
}
We can try with Photos Framework to fetch the last saved image.
var fetchOptions: PHFetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
var fetchResult = PHAsset.fetchAssetsWithMediaType(PHAssetMediaType.Image, options: fetchOptions)
if (fetchResult.firstObject != nil) {
var lastAsset: PHAsset = fetchResult.lastObject as! PHAsset
PHImageManager.defaultManager().requestImageForAsset(lastAsset, targetSize: self.UploadImagePreview.bounds.size, contentMode: PHImageContentMode.AspectFill, options: PHImageRequestOptions(), resultHandler: { (result, info) -> Void in
self.UploadImagePreview.image = result
})
}

Resources