iPhoneアプリ開発

【Swift】バックグラウンド処理でWebから画像取得しViewにセット

バックグラウンド処理で、指定したURLの画像をアプリ上にViewとして表示する。

 

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    // Background operations
 
    dispatch_async(dispatch_get_main_queue(), ^{
          // Main Thread
    });
});

今回は上記の「Background operations」で画像を取得する処理、「Main Thread」でViewを追加する処理を行う。

URLの画像を取得するのは以下コード(Background operations)

// NSURLを取得
let url = NSURL(string: "http://~");
let imgData: NSData
var webImage: UIImage

// Webから画像取得
do {
    imgData = try NSData(contentsOfURL:url!,options: NSDataReadingOptions.DataReadingMappedIfSafe)
    webImage = UIImage(data:imgData)!;
    
} catch {
    print("Error: can't create image.")
}

 

取得した画像を表示したいViewに追加(Main Thread)

// UIImageView インスタンスの生成
let iconView = UIImageView(image:webImage)
// サイズを調整
iconView.frame.size = CGSizeMake(60, 60)
// 好きなViewに追加
self.view.addSubview(iconView)