varinder singh
varinder singh

Reputation: 43

Loading large size images makes app crashes in Swift 2.0

I am making an iOS app that shows the wedding images of the users. The average size of a image file is about 1.5 Mb. But when the images exceed(more than 10 images) app crashes. Is there any solution to solve this problem? I was thinking of implementing core data. Will it help? If not please help me then.

This is my code

func webservice() { let url = NSString (format: "http://webphotobooks.in/webphotobook/index.php/web_controller/fetch1?id=%@&album_id=%@",self.userId,self.albumId)

    let  urlString :String = url.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
    //print(urlString, terminator: "")

    let request : NSMutableURLRequest = NSMutableURLRequest()
    request.URL = NSURL(string: urlString as String)
    request.HTTPMethod = "GET"

    var response: NSURLResponse?

    let data = (try? NSURLConnection.sendSynchronousRequest(request, returningResponse: &response)) as NSData?

    if let httpResponse = response as? NSHTTPURLResponse {
        //print("error \(httpResponse.statusCode)")

        let statusCode = httpResponse.statusCode
        if statusCode == 200
        {
            do
            {
                let jsonResult: NSDictionary! = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers) as! NSDictionary
                //print(jsonResult, terminator: "")

                if (jsonResult != nil)
                {

                    if (jsonResult?.objectForKey("messagge") as! String == "successfull")
                    {
                        self.array = jsonResult.valueForKey("images") as! NSArray
                       // print(self.array)

                        self.collectionView.reloadData()
                    }

                    else
                    {
                        if #available(iOS 8.0, *) {
                            let alert = UIAlertController(title: "Error", message: "Unable to fetch images", preferredStyle: UIAlertControllerStyle.Alert)

                            alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
                            alert.view.tintColor = UIColor.blackColor()

                            self.presentViewController(alert, animated: true, completion: nil)

                        }
                        else
                        {
                            let alert = UIAlertView(title: "Error", message: "Unable to fetch images", delegate: self, cancelButtonTitle: "Ok")
                            alert.show()
                        }

                    }
                }
            }
            catch let error as NSError
            {
                print(error)
            }
        }
        else
        {
            if #available(iOS 8.0, *) {
                let alert = UIAlertController(title: "Error", message: "Please check your internet connection", preferredStyle: UIAlertControllerStyle.Alert)

                alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
                alert.view.tintColor = UIColor.blackColor()

                self.presentViewController(alert, animated: true, completion: nil)

            }
            else
            {
                let alert = UIAlertView(title: "Error", message: "Please check your internet connection", delegate: self, cancelButtonTitle: "Ok")
                alert.show()
            }

        }
    }

}


func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    //#warning Incomplete method implementation -- Return the number of sections
    return 1
}


func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    //#warning Incomplete method implementation -- Return the number of items in the section
    return self.array.count
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
    let cell:HomeCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("HomeCell", forIndexPath: indexPath) as! HomeCollectionViewCell
    if let images = cell.profileImage
    {
        if !(array.valueForKey("image_name").objectAtIndex(indexPath.row).isKindOfClass(NSNull))
        {
            let Str = array.valueForKey("image_name").objectAtIndex(indexPath.row) as! String

            let block: SDWebImageCompletionBlock! = {(image: UIImage!, error: NSError!, cacheType: SDImageCacheType, imageURL: NSURL!) -> Void in
                // print(image) 
            }
            let urlStr = NSString(format: "http://webphotobooks.in/admin/uploads/category_pics/%@", Str)
            //print(urlStr)
            let urlString :String = urlStr.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
            //print(urlString)
            let url = NSURL(string: urlString as String)
            //print(url)

            images.sd_setImageWithURL(url, completed: block)
        }
    }
    actInd.stopAnimating()
    return cell
}

Upvotes: 0

Views: 1590

Answers (2)

Amrit Sidhu
Amrit Sidhu

Reputation: 1950

The will definitely crash since you are consuming too much of the memory. The only solution for this is either fetch small sized images or compress the image after fetching them. You cannot load all full sized images into the memory. The backend has many options for compressing the images. You can compress the images at the backend itself, that might reduce your work in the app.

You might also want to see the actual image. Then you can download the actual image after tapping the image.Initially you should fetch smaller images. Every application does the same. There are many open source image cache libraries that can even handle the caching for this purpose. One such example is SD-WebImage

Upvotes: 1

Andrea
Andrea

Reputation: 26385

The average size of an image is about 1.5 Mb

This is the file size not the image size, if it is jpg is probably also compressed. Once open in memory an image takes num_pixel_height * num_pixel_width * num_channel * bit_for_channel. For instance an image RGBA with 8bit for channel 200px * 200px is about 625kb, but the file size due to compression can be a lot smaller.

Upvotes: 1

Related Questions