I am developing my first app where user can save 13 screenshots and swipe between in one view controller (full size images) and display them together as thumbnails on another view controller. This above is how I save my 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()
Following is how I retrieve images. This is code for the first screenshot and setting it as a image in UIImageView (done similarly for 12 other UIImageViews):
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 )
Sticker1_view.image = resizeImage(image!, newSize: CGSizeMake(overView.frame.width/4, overView.frame.height/4))
This is how I scale them down after they are loaded to memory:
func resizeImage(image: UIImage, newSize: CGSize) -> (UIImage) {
let newRect = CGRectIntegral(CGRectMake(0,0, newSize.width, newSize.height))
let imageRef = image.CGImage
UIGraphicsBeginImageContextWithOptions(newSize, false, 0)
let context = UIGraphicsGetCurrentContext()
// Set the quality level to use when rescaling
CGContextSetInterpolationQuality(context, kCGInterpolationHigh)
let flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, newSize.height)
CGContextConcatCTM(context, flipVertical)
// Draw into the context; this scales the image
CGContextDrawImage(context, newRect, imageRef)
let newImageRef = CGBitmapContextCreateImage(context) as CGImage
let newImage = UIImage(CGImage: newImageRef)
// Get the resized image from the context and a UIImage
UIGraphicsEndImageContext()
return newImage!
}
The app works fine first time. But as I switch between the two view controllers it gets slow and ultimately I get a memory warning which leads to a crash. From what I understand from researching is that my images are getting cached. I need to clear my cache or do not multiple load my images. Or maybe do something in didReceiveMemoryWarning() in order to stop it from crashing. What should I do ?