iOS 앱의 원격 데이터가있는 테이블 뷰를 구축 중입니다. 나는 AlamoFire와 SwiftyJSON을 사용하여 여러 개의 에피소드로 JSON 파일을로드합니다.Alamofire를 사용하여 JSON의 URL을 사용하여 이미지로드하기
JSON 파일은 다음과 같이 구성되어있다 :
{
"id": "456",
"name": "EpOne",
"description": "Episode description 1",
"imageURL": "http://myimage.com/myimagefile1.jpg"
},
{
"id": "789",
"name": "Eptwo",
"description": "Episode description 2",
"imageURL": "http://myimage.com/myimagefile2.jpg"
} ...
그래서 내가있는 viewDidLoad에서
getEpisodes(url: endpoint)
를 호출합니다. 이것은 다음을 실행합니다
func getEpisodes(url: String) {
Alamofire.request(url, method: .get).validate().responseJSON { response in
switch response.result {
case .success(let value):
let json = JSON(value)
self.buildEpisodeArray(json: json)
case .failure(let error):
print(error)
}
}
}
func buildEpisodeArray(json: JSON) {
if let allEpisodes = json["episodes"].array {
for singleEpisode in allEpisodes {
let currentEpisode = Episode()
currentEpisode.name = singleEpisode["name"].string!
currentEpisode.imageURL = singleEpisode["imageURL"].string!
episodes.append(currentEpisode)
}
}
tableView.reloadData()
}
그런 다음 나는 모든 것이 잘 작동이 시점에서 내 세포
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "Cell"
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! EpisodeCell
cell.nameLabel.text = episodes[indexPath.row].name
// TODO Get the image
return cell
}
에 데이터를로드합니다. 문제는 이미지를로드하려고 할 때입니다. 나는 약간의 튜토리얼을 체크했다 (나는 이것의 새로운 종류이다). 그리고 Alamofire로 데이터를 얻은 후에, 그들은 contentsOf : url을 사용하여 이미지를 얻는다. 내 경우에는, 내가 대체 할 그래서이 이미지를로드하지만, 테이블 뷰가 메가 느
// Get the image
if let url = NSURL(string: episodes[indexPath.row].imageURL),
let data = NSData(contentsOf: url as URL) {
cell.episodeImage.image = UIImage(data: data as Data)
}
에 "// TODO 이미지를 가져옵니다." 하지만, contentsOf : url을 사용하지 않는 이유는 alamofire로 데이터를로드하는 데 따른 이점 때문입니다 (위와 아래로 스크롤 할 때 테이블이 너무 느린 이유라고 생각합니다).
이미지를 비동기 적으로로드하면 안됩니까? 그렇다면 각 이미지에 대해 별도의 Alamofire.request를 만들 수 있습니까?
Alamofire 및 기타 이미지로드를위한 자습서를 찾았지만 데이터를로드하고 해당 데이터와 함께로드 할 이미지를로드하려면 어떻게해야합니까?
도움을 주셔서 감사합니다.
덕분에 좋은 일! :디 – cesarcarlos