I have a function that turns out be too slow to run on main thread (200ms). This function is used to determine the size of the image.
extension : UIImage {
var dataLengh_kb: Int {
return (UIImageJPEGRepresentation(self, 1.0)?.length)! / 1024
}
}
I am using in various places of my app and especially in the following example
func someFunction() {
if img.dataLength_kb > MAX_SIZE {
// Upload to server
} else {
someImageView.image = img
}
functionFinished()
}
Since it is too slow, I am thinking to put it in background thread in two ways I am not sure what the difference and impact to my app is either way.
Method 1:
extension : UIImage {
var size: Float!
var dataLengh_kb: Int {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
size = UIImageJPEGRepresentation(self, 1.0)?.length)! / 1024
dispatch_async(dispatch_get_main_queue(), ^{
return size
})
})
}
Method 2:
extension : UIImage {
var size: Float!
var dataLengh_kb: Int {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
return UIImageJPEGRepresentation(self, 1.0)?.length)! / 1024
dispatch_async(dispatch_get_main_queue(), ^{
})
})
}
My question is
If I go with method 2, does that mean all my code after dataLengh_kb will be in background thread which is bad?
If I go with either method 1 or method 2, does that mean functionFinished() will be executed too early ?
Both method 1 and method 2 complains that I am not returning an Int Value as it is expected to return 'Int'