Created
February 14, 2019 03:34
-
-
Save yoheiMune/12b4cc4ed72d1d472956f4de2a532942 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// UIImageViewの拡張. | |
extension UIImageView { | |
// 指定URLから画像をダウンロードして、表示します(ダウンロード先を文字列で指定). | |
func downloadedFrom(path: String, contentMode mode: UIView.ContentMode = .scaleAspectFit) { | |
// http:// から始まるフルパスにする. | |
let urlString = apiRoot + path | |
guard let url = URL(string: urlString) else { return } | |
downloadedFrom(url: url, contentMode: mode) | |
} | |
// 指定URLから画像をダウンロードして、表示します. | |
func downloadedFrom(url: URL, contentMode mode: UIView.ContentMode = .scaleAspectFit) { | |
contentMode = mode | |
// ダウンロード先にリクエストを発行します. | |
URLSession.shared.dataTask(with: url) { data, response, error in | |
// 正しくHTTP通信ができたことを確認します. | |
guard | |
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200, | |
let mimeType = response?.mimeType, mimeType.hasPrefix("image"), | |
let data = data, error == nil, | |
let image = UIImage(data: data) | |
else { return } | |
DispatchQueue.main.async() { | |
// メインスレッドで、表示する画像の更新を行います. | |
self.image = image | |
} | |
}.resume() | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
class TimelineCell : UITableViewCell { | |
@IBOutlet weak var avatarImageView: UIImageView! | |
@IBOutlet weak var userNameLabel: UILabel! | |
@IBOutlet weak var photoImageView: UIImageView! | |
@IBOutlet weak var bodyLabel: UILabel! | |
// 投稿データ. | |
var post: Post? { | |
// 値がセットされたら | |
didSet { | |
// 値がなければそれで終わり. | |
guard let post = post else { | |
return | |
} | |
// 投稿画像を読み込むまでは、ダミーを表示することとする. | |
self.photoImageView.image = UIImage(named: "default") | |
// ユーザー名. | |
self.userNameLabel.text = post.user.name | |
// ユーザーアバター画像. | |
self.avatarImageView.downloadedFrom(path: post.user.avatar_url) | |
// 投稿画像. | |
self.photoImageView.downloadedFrom(path: post.image_url) | |
// 投稿本文. | |
self.bodyLabel.text = post.body | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment