ios - 加载大尺寸图像会使应用程序在 Swift 2.0 中崩溃

标签 ios swift crash out-of-memory image-size

我正在制作一个 iOS 应用程序来显示用户的婚礼照片。图像文件的平均大小约为 1.5 Mb。但是当图像超过(超过 10 张图像)应用程序崩溃时。有什么办法可以解决这个问题吗? 我正在考虑实现核心数据。会有帮助吗?如果没有,请帮助我。

这是我的代码

函数网络服务() { 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
}

最佳答案

The average size of an image is about 1.5 Mb

这是文件大小而不是图像大小,如果是 jpg 可能也被压缩了。一旦在内存中打开,图像将采用 num_pixel_height * num_pixel_width * num_channel * bit_for_channel。例如, channel 200px * 200px 的 8 位 RGBA 图像大约为 625kb,但压缩后的文件大小可能小得多。

关于ios - 加载大尺寸图像会使应用程序在 Swift 2.0 中崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36325172/

相关文章:

html - 从桌面浏览器到移动浏览器的莫名其妙的字体大小变化

ios - 缺少 64 位支持和 Lipo 错误!!无法在 Xcode 6.3 中打开输入文件

ios - 我可以使用 NSURLSessionUploadTask 进行离线同步任务吗?

ios - 不使用自动布局时,PrepareForSege崩溃

ios - 验证 iOS 屏幕是否存在用户错误

ios - 如何使用 SwiftUI 制作自定义图像 resizable()

ios - 根据 NSString 值的匹配从 NSMutableDictionary 中删除条目

ios - 在 Swift 中限制没有 query.limit 的解析查询

swift - 当字典键上的 Swift "if let ... "失败时会发生什么?

crash - 寻找解决方案Mariadb表因系统突然断电而崩溃