I am trying to use the last image from the camera roll as the background image for my UIButton. When the view loads up the button shows the last photo correctly. But when I snap a picture the background image in the UIbutton is not updated. Here is the code I am using to get the last photo
func lastPhoto() {
let imgManager = PHImageManager.defaultManager()
var fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key:"creationDate", ascending: true)]
if let fetchResult = PHAsset.fetchAssetsWithMediaType(PHAssetMediaType.Image, options: fetchOptions) {
imgManager.requestImageForAsset(fetchResult.lastObject as PHAsset, targetSize: self.view.frame.size, contentMode: PHImageContentMode.AspectFill, options: nil, resultHandler: { (image, _) in
self.rollBtn.setBackgroundImage(image, forState: .Normal)
})
}
}
not sure if it is relevant, but here is the snippet of code I use to take the photo
switch (camMgr.cameraOutputMode) {
case .StillImage:
camMgr.capturePictureWithCompletition({ (image, error) -> Void in
if let capturedImage = image? {
println("capture image")
//animate button effect
UIView.animateWithDuration(0.3, animations: {
sender.backgroundColor = UIColor.greenColor()
}, completion: {(finished:Bool) in
println("inside")
sender.backgroundColor = UIColor.whiteColor()
self.lastPhoto()
})
UIView.animateWithDuration(0.1, animations: {
self.buttonView.backgroundColor = UIColor.blackColor()
}, completion: {(finished:Bool) in
println("inside")
self.buttonView.backgroundColor = UIColor.clearColor()
self.lastPhoto()
})
}
})
case .VideoWithMic, .VideoOnly:
sender.selected = !sender.selected
sender.backgroundColor = sender.selected ? UIColor.redColor() : UIColor.greenColor()
if sender.selected {
camMgr.startRecordingVideo()
} else {
camMgr.stopRecordingVideo({ (videoURL, error) -> Void in
println(videoURL)
if let errorOccured = error? {
UIAlertView(title: "Error occured", message: errorOccured.localizedDescription, delegate: nil, cancelButtonTitle: "OK").show()
}
})
}
}
}
I am still new to this whole coding thing, please any help would be nice. Thank you kindly.
Try this, I am not sure you need to fetch the last photo. Just update the UIButton background image like so. Should give the effect you are after. Let me know if it fixed it.
if let capturedImage = image? {
println("capture image")
//animate button effect
UIView.animateWithDuration(0.3, animations: {
sender.backgroundColor = UIColor.greenColor()
}, completion: {(finished:Bool) in
println("inside")
sender.backgroundColor = UIColor.whiteColor()
})
UIView.animateWithDuration(0.1, animations: {
self.buttonView.backgroundColor = UIColor.blackColor()
}, completion: {(finished:Bool) in
println("inside")
self.buttonView.backgroundColor = UIColor.clearColor()
self.rollBtn.setBackgroundImage(capturedImage, forState: .Normal)
})
}
})