LoginSignup
41
38

More than 5 years have passed since last update.

SDWebImageをiOS9で使う(Xcode7)

Last updated at Posted at 2015-10-22

SDWebImageとは

https://github.com/rs/SDWebImage
SDWebImageというライブラリがあり、cocoapodsから導入できます

iOS開発で使えて、

imageView.sd_setImageWithURL(NSURL(string: "https://pbs.twimg.com/profile_images/648801531702083584/nqCFf1AY.png"))

みたいに書くだけで、画像を非同期ダウンロード&キャッシュを行ってくれます!キャッシュ期間なども設定可能で、とても便利に利用できます。

ただ、Xcode7にしてから動かなく(画像が表示されなく)なって・・・原因はなんだろう、と思っていたら、Xcodeではなく、iOS9のATSが原因でした・・・(詳しくは後述します)

install

cocoapodsがインストールされていない場合、クリーンなMacOSX 10.11に開発環境をを参考に、cocoapodsをインストール!

普通にcocoapodsで

Podfile
platform :ios, '8.0'
use_frameworks!

pod 'SDWebImage'

として、pod installすればOKです

ちなみに、use_frameworks!、とかくと、swift用という意味になり、ver0.36以前では必要であったブリッジファイルを記述する必要がなくなります
参考 → Swift 対応版 CocoaPods を使う

iOS9での簡単な使い方

SDWebImageの細かい使い方はほかのサイトに多くあると思いますので、割愛します。

sample -> https://github.com/ha1fha1f/SDWebImageTest

上のgitにサンプルのプロジェクトをおきました(Xcode7.1)

iOS9で動かないのはATSが原因ですので、とりあえず動かしたいのであれば、ATSを切ればよいのです・・・

すなわち、特定ドメインに対するATSを無効化するおまじない

Info_plist.png

これをInfo.plistに記述すればOKです。
pbs.twimg.comのところは、画像を取得したい先のドメインにしておいてください。

xmlで以下を記述したほうが速いかもしれません、

<key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <false/>
        <key>NSExceptionDomains</key>
        <dict>
            <key>(ドメイン名)</key>
            <dict>
                <key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
                <false/>
                <key>NSExceptionAllowsInsecureHTTPLoads</key>
                <true/>
            </dict>
        </dict>
    </dict>

これで無理矢理ではありますが、iOS9でもSDWebImageを使うことができます

ViewControllerのコードは、SDWebImageはUIImageViewがextensionされて実装されているので、

class ViewController: UIViewController {
    var imageView: UIImageView! = nil

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        if imageView == nil {
            imageView = UIImageView(frame: self.view.frame)
            imageView.backgroundColor = UIColor.blueColor()
            imageView.sd_setImageWithURL(NSURL(string: "https://pbs.twimg.com/profile_images/648801531702083584/nqCFf1AY.png"))
            imageView.contentMode = UIViewContentMode.ScaleAspectFit
            self.view.addSubview(imageView)
        }
    }
}

これだけでOKです
とても簡単ですね!

41
38
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
41
38