質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

Q&A

解決済

1回答

329閲覧

Photos frameworkを使って端末内のアルバムの画像をUIImageの配列として取得したい

pftyuk

総合スコア52

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

0グッド

0クリップ

投稿2019/01/19 03:07

編集2019/01/21 14:38

前提・実現したいこと

Photos frameworkを使って端末内のアルバムの画像をUIImageの配列として取得したいです。

こちらを参考にして、実装を行ったのですが実行時にエラーで落ちてしまいます。
調べた限りメモリリークに関するエラーのようですが、解決方法がわからなかったので
ご教示頂ければ幸いです。

発生している問題・エラーメッセージ

2019-01-19 11:56:15.097534+0900 GemCamera[8198:2560115] [ImageManager] First stage of an opportunistic image request returned a non-table format image, this is not fatal, but it is unexpected Message from debugger: Terminated due to memory issue

該当のソースコード

Swift

1class AlbumViewController: UIViewController { 2 var assets:[PHAsset] = [] 3 var selectedAsset:PHAsset? = nil 4 5 @IBOutlet weak var albumCollectionView: GeminiCollectionView!{ 6 didSet{ 7 let cellIdentifier = "AlbumCollectionViewCell" 8 let nib = UINib(nibName: cellIdentifier, bundle: nil) 9 albumCollectionView.register(nib, forCellWithReuseIdentifier: cellIdentifier) 10 albumCollectionView.delegate = self 11 albumCollectionView.dataSource = self 12 13 albumCollectionView.gemini 14 .circleRotationAnimation() 15 .radius(450) 16 .rotateDirection(.clockwise) 17 .itemRotationEnabled(true) 18 } 19 } 20 21 override func viewDidLoad() { 22 super.viewDidLoad() 23 assets = getAssetsInAlbum() 24 25 if let layout = albumCollectionView.collectionViewLayout as? UICollectionViewFlowLayout { 26 layout.scrollDirection = .vertical 27 albumCollectionView.collectionViewLayout = layout 28 } 29 } 30 31 private func getAssetsInAlbum()->[PHAsset]{ 32 var assets:[PHAsset] = [] 33 34 let options = PHFetchOptions() 35 let fetchResult = PHAsset.fetchAssets(with: .image, options: options) 36 fetchResult.enumerateObjects { (asset, index, stop) -> Void in 37 assets.append(asset) 38 } 39 40 return assets 41 } 42 43 // MARK: - Navigation 44 45 // In a storyboard-based application, you will often want to do a little preparation before navigation 46 override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 47 if segue.identifier == "toPhotoPreView"{ 48 let photoViewController = segue.destination as! PhotoPreViewController 49 photoViewController.selectedAsset = selectedAsset 50 } 51 } 52} 53 54// MARK: - UIScrollViewDelegate 55extension AlbumViewController { 56 func scrollViewDidScroll(_ scrollView: UIScrollView) { 57 albumCollectionView.animateVisibleCells() 58 } 59} 60 61// MARK: - UICollectionViewDelegate 62extension AlbumViewController: UICollectionViewDelegate { 63 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { 64 selectedAsset = assets[indexPath.row] 65 performSegue(withIdentifier: "toPhotoPreView", sender: nil) 66 } 67 68 func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { 69 if let cell = cell as? GeminiCell { 70 self.albumCollectionView.animateCell(cell) 71 } 72 } 73} 74// MARK: - UICollectionViewDataSource 75extension AlbumViewController:UICollectionViewDataSource{ 76 func numberOfSections(in collectionView: UICollectionView) -> Int { 77 return 1 78 } 79 80 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 81 return assets.count 82 } 83 84 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 85 let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "AlbumCollectionViewCell", for: indexPath) as! AlbumCollectionViewCell 86 cell.configure(with: assets[indexPath.row]) 87 self.albumCollectionView.animateCell(cell) 88 return cell 89 } 90} 91 92// MARK: - UICollectionViewDelegateFlowLayout 93extension AlbumViewController: UICollectionViewDelegateFlowLayout { 94 private enum Const { 95 static let collcetionViewSize = CGSize(width: UIScreen.main.bounds.size.width * 0.7, height: UIScreen.main.bounds.size.height * 0.7) 96 } 97 98 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { 99 return Const.collcetionViewSize 100 } 101 102 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { 103 guard let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout else { 104 return UIEdgeInsets(top: 50, left: 50, bottom: 50, right: 50) 105 } 106 107 switch layout.scrollDirection { 108 case .horizontal: 109 110 let verticalMargin: CGFloat = (collectionView.bounds.height - Const.collcetionViewSize.height) / 2 111 return UIEdgeInsets(top: 50 + verticalMargin, 112 left: 50, 113 bottom: 50 + verticalMargin, 114 right: 50) 115 case .vertical: 116 117 let horizontalMargin: CGFloat = (collectionView.bounds.width - Const.collcetionViewSize.width) / 2 118 return UIEdgeInsets(top: 50, 119 left: 50 + horizontalMargin, 120 bottom: 50, 121 right: 50 + horizontalMargin) 122 } 123 } 124 125 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { 126 return 10 127 } 128 129 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { 130 return 0 131 } 132}
class AlbumCollectionViewCell: GeminiCell { @IBOutlet weak var image: UIImageView! override func awakeFromNib() { super.awakeFromNib() // Initialization code } func configure(with asset:PHAsset ) { var photoImage:UIImage? = nil let targetSize = CGSize(width: self.bounds.width, height: self.bounds.height) let manager = PHImageManager() manager.requestImage(for: asset, targetSize: targetSize, contentMode: .aspectFit,options: nil){ (image, info) in if image != nil{ photoImage = image } } self.image.image = photoImage } }

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

これは、アルバム内の全ての写真をフルサイズで取得して配列に格納しようとしていますから、
たくさん写真が入っているiPhoneで実行したら当然メモリ不足になると思います。
iPhoneのカメラで撮影した写真をオリジナルサイズでUIImageに読み込んだら、
4032x3024x4=約48MBのメモリを消費します。それが10枚あったら480MBの
メモリ消費です。

実際に表示が必要になった場面で必要な写真だけ読み込むように設計する必要があると思います。

投稿2019/01/20 15:37

編集2019/01/20 17:53
TakeOne

総合スコア6299

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

pftyuk

2019/01/20 15:51

ご回答頂きありがとうございます。 メモリ不足で落ちてしまっていたのですね・・・。ご説明頂いた内容で納得しました。 こちらの情報不足で大変恐縮なのですが、最終的にやりたいこととしては https://github.com/shoheiyokoyama/Gemini こちらのライブラリを使ってアルバム内の写真を表示したいです。 中身はcollectionViewになっていて、写真一枚一枚がcollectionViewCellになっているので 表示にあたりアルバム内の画像データの全部を取得する必要があると思うのですが >実際に表示が必要になった場面で必要な写真だけ読み込むように設計する必要があると思います。 こちら手立てとして、どのような解決方法がありますでしょうか・・・。 いきなりUIImageの配列で持たずに、画像のデータ(?)を配列で持っておいて 画面に表示されるセルにだけUIImageを生成して当ててあげれば宜しいでしょうか・・・?
TakeOne

2019/01/20 16:14

image(UIImage)の配列を保持するのではなく、asset(PHAsset)の配列を保持し、表示が必要になった段階(セル生成時)でassetを使って画像を読み込めばよいと思います。また、画像サイズも画面に表示するのに十分なサイズがあればいいのだから、フルサイズの画像を読み込むべきではないと思います。
pftyuk

2019/01/21 14:47

ご回答頂きありがとうございます。 お答え頂いた方法で無事アルバム内の画像を全て表示することができました! しかしどうも表示されている画像の解像度が悪く、全て粗く表示されてしまいました。 手元で原因を調べてみたのですが解決まで至らなかったため 重ねての質問で恐縮ですがご教示頂けませんでしょうか・・・。 試したこととしては、セルに画像をセットしているconfigure内の contentModeをaspectFit→aspectFillに変更してみましたが粗いことは変わりませんでした。
TakeOne

2019/01/22 15:04

targetSizeをself.bounds(セルの大きさ)から取得していますが、collectionViewに乗せる前の段階でこのセルの大きさが意図した大きさにレイアウト調整されているか、`self.bounds`をprintして確認すべきと思います。 また、そのサイズが意図したポイント数であったとしても、Retinaディスプレイは実際にはそのx2かx3のピクセル数になりますから、scaleを掛けたサイズをtargetSizeにしないと、非Retinaディスプレイで表示した時の画像の粗さになってしまうと思います。contentModeは粗さには関係ないと思います。
pftyuk

2019/01/22 15:38 編集

返信ありがとうございます。 早速試してみましたが結果が変わりませんでした。 まずself.boundsをprintしてみましたが意図しているポイント数になっていました。 わかりやすいようにセルの大きさを固定値にして確認してみました。 scaleを掛けたサイズをtargetSizeにとのことですが let scale = CGFloat(3.0) let targetSize = CGSize(width: self.bounds.width * scale, height: self.bounds.height * scale) このように変更してみました。(解釈が違っていたらご指摘下さい) 上記で解決しないとなると、別のところに原因があるのでしょうか・・・。 追記 写真を表示しているセルはxibで作成しており、セルの上にImageViewが乗っているのですが このImageViewのcontent ModeはAspectFillになっております(関係があるかわかりませんが・・・)
TakeOne

2019/01/22 15:44

``` manager.requestImage(for: asset, targetSize: targetSize, contentMode: .aspectFit,options: nil){ (image, info) in if image != nil{ photoImage = image } } self.image.image = photoImage ``` これって、よく見るとクロージャの外で`self.image.image`に画像を設定してますが、本当にこれで画像が表示できてるんですか? クロージャの中で `photoImage = image`をした直後に `self.image.image = photoImage`をする必要があると思います。
pftyuk

2019/01/23 13:32

返信ありがとうございます。 まさに仰る通り、クロージャの外で画像をセットしていた部分を クロージャ中で画像をセットするように変更したところ、うまく表示されるようになりました! ただ一部の画像だけ荒いままでそちらは別問題な気がしますので自分で調べてみます。 興味の範疇なのでご存知であればお答え頂ければ幸いなのですが 何故クロージャの外でセットした場合と中でセットした場合で違いが出たのでしょうか・・・。 一旦こちらについて、ベストアンサーとさせて頂き閉じさて頂きます。 この度はありがとうございました!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問