Loading multiple saved images in app slows it down

139 views Asked by At

I am developing an app where user can save 13 screenshots and display them on a single view as thumbnails or as a full screen image.

let fileName:String = self.stickerUsed + ".png"
var arrayPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
var pngFileName = arrayPaths.stringByAppendingPathComponent(fileName)
UIImagePNGRepresentation(screenshot).writeToFile(pngFileName, atomically:true)
NSUserDefaults.standardUserDefaults().setObject(fileName, forKey: self.stickerUsed)
NSUserDefaults.standardUserDefaults().synchronize()

This above is how I save my image and this following is how I retrieve images. This is code for the first screenshot:

var defaultName:String = "Sticker1.png"
let path = NSSearchPathForDirectoriesInDomains(
    .DocumentDirectory, .UserDomainMask, true)[0] as NSString
let fileName = NSUserDefaults.standardUserDefaults()
    .stringForKey("Sticker1") ?? defaultName
let imagePath = path.stringByAppendingPathComponent(fileName)
let image = UIImage(contentsOfFile: imagePath )

The problem is that displaying them in a single view gets really slow as number of screenshot increases. Eventually the app crashes after showing "Received memory warning". I am new to swift and app development. What is the right way to display all these images in a thumbnail without slowing down or crashing and also saving the image in full resolution.

1

There are 1 answers

2
Yuchen On BEST ANSWER

The problem with the following code is that you will have all your images in full resolution:

let image = UIImage(contentsOfFile: imagePath )

It is better to scale it down immediately and make the thumbnail after it is loaded into the memory:

// This line is still the same
let image = UIImage(contentsOfFile: imagePath )

// Scale the image down: 
let newSize = ... // Defined the new size here
                  // should probably be a good idea to match 
                  // the size of the UIImageView
UIGraphicsBeginImageContext(newSize)
image.drawInRect(CGRect(origin: CGPointZero, size: newSize))
image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

See more: link.