2016-03-31 62 views
0

我正在製作一個顯示用戶婚禮圖像的iOS應用程序。圖像文件的平均大小約爲1.5 Mb。但是,當圖像超過(超過10個圖像)應用程序崩潰。有沒有解決這個問題的方法? 我正在考慮實施核心數據。它會有幫助嗎?如果不是,請幫助我。加載大尺寸圖片使Swift 2.0中的應用程序崩潰

這是我的代碼

FUNC web服務() { 設URL =的NSString(格式: 「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 
} 
+0

顯示您的代碼以及它如何崩潰。嘗試使用'UIImage(contentsOfFile:)'initializer加載它們 –

+0

我正在使用SDWebImages來加載圖像 –

回答

1

平均尺寸的圖像大約是1.5 Mb

這是文件大小不是圖像大小,如果它是JPG也可能壓縮。一旦在內存中打開,圖像需要num_pixel_height * num_pixel_width * num_channel * bit_for_channel。例如,對於通道200px * 200px 8bit的圖像RGBA大約爲625kb,但由於壓縮造成的文件大小可能會小很多。

+0

你能舉個例子嗎? –

+0

我已經做了,由於內存壓力,你的應用程序崩潰。它無法處理10個具有該尺寸的圖像。如果你想要明確的答案,你應該通過添加額外的數據,代碼等來澄清你的問題。例如,你是否需要一次顯示所有10張圖片?你如何擺脫它們? – Andrea

1

由於您消耗的內存太多,所以肯定會崩潰。唯一的解決方法是獲取小尺寸的圖像或在獲取圖像後壓縮圖像。您無法將所有全尺寸圖像加載到內存中。後端有許多壓縮圖像的選項。您可以在後端壓縮圖像本身,這可能會減少您在應用程序中的工作。

您可能還想看到實際的圖像。然後,您可以在點擊圖像後下載實際圖像。最初您應該獲取較小的圖像。每個應用程序都是一樣的。有許多開源圖像緩存庫甚至可以爲此處理緩存。一個這樣的例子是SD-WebImage

相關問題