2016-03-31 4 views
0

私は、ユーザーの結婚式イメージを表示するiOSアプリを作成しています。画像ファイルの平均サイズは約1.5Mbです。しかし、画像が(10以上の画像)アプリクラッシュを超えるとき。この問題を解決するソリューションはありますか? 私はコアデータを実装することを考えていました。助けてくれる?もしそうでないなら、私を助けてください。大きなサイズの画像を読み込むと、Swift 2.0でアプリがクラッシュする

これは私のコード

FUNCのWebサービス(){ LETの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:)'イニシャライザを使用してロードしてみてください –

+0

私は画像をロードするためにSDWebImagesを使用しています –

答えて

1

平均サイズのイメージは約1.5Mbです

これはjpgのファイルサイズでもあります圧縮される。メモリに一度開くと、画像はnum_pixel_height * num_pixel_width * num_channel * bit_for_channelになります。たとえば、チャンネル200px * 200pxの8bit画像RGBAは約625kbですが、圧縮によるファイルサイズはかなり小さくなります。

+0

私に例を挙げてください。 –

+0

私はすでに、メモリ圧迫のためにあなたのアプリケーションがクラッシュしました。そのサイズの画像は10枚も処理できません。明確な答えが必要な場合は、データ、コードなどを追加して質問を明確にする必要があります。たとえば、10枚の画像を一度に表示する必要がありますか?どのようにそれらを取り除く? – Andrea

1

あまりにも多くのメモリを消費しているため、間違いなくクラッシュします。このための唯一の解決策は、小さなサイズのイメージをフェッチするか、フェッチした後イメージを圧縮することです。すべてのフルサイズのイメージをメモリに読み込むことはできません。バックエンドには、画像を圧縮するための多くのオプションがあります。バックエンドで画像を圧縮すると、アプリ内の作業が減少する可能性があります。

また、実際の画像を見ることもできます。その後、イメージをタップした後に実際のイメージをダウンロードすることができます。最初に小さなイメージをフェッチする必要があります。すべてのアプリケーションは同じです。この目的のためにキャッシングを扱うことができるオープンソースのイメージ・キャッシュ・ライブラリはたくさんあります。そのような例の1つがSD-WebImageです。

関連する問題