내 웹 서비스를 호출하여 JSON 데이터를 반환하면 UICollectionView에서 셀을 채우는 데 사용됩니다. 셀 수를 결정하기 위해 JSON 배열에 반환 된 항목 수를 계산합니다. 그러나 문제는 내 dataTask () 함수가 완료되기 전에 내 collectionView () 함수가 호출된다는 것입니다 (내 추측은 dataTask ()가 비동기 적이라는 것입니다), 차례로 nil 값 (jsonCount)에 액세스하고 있음을 자세히 설명하는 오류를 제공합니다. TestController.swift의 변수). 다양한 completeHandlers 및 반환 값을 가지고 놀아 보았지만 작동하지 않습니다. 제발 올바른 방향으로 안내해 주시겠습니까?
귀하의 도움 / 의견은 대단히 감사합니다.
HomeModel.swift
class func getPostings(completionHandler: @escaping (_: Any) -> ()) {
let url: URL = URL(string: "url")!
let request: URLRequest = URLRequest(url: url)
let task = URLSession.shared.dataTask(with: request) {data,
response, error in
guard error == nil else {
print(error!)
completionHandler("Failed")
return
}
let httpResponse = response as! HTTPURLResponse
let statusCode = httpResponse.statusCode
if statusCode == 200 {
let json = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [[String: Any]]
completionHandler(json!)
}
}
task.resume()
TestController.swift
var jsonCount: Int?
var jsonData: [[String: Any]]?
override func viewDidLoad() {
super.viewDidLoad()
HomeModel.getPostings(completionHandler: {(response: Any) -> Void in
guard response as? String != "Failed" else {
//Code to send a pop-up alert to the user
return
}
self.jsonData = response as? [[String: Any]]
self.jsonCount = (self.jsonData?.count)!
})
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return jsonCount
}
CollectionView
또는 TableView
기본적으로 ViewDidLoad
메서드에서 다시로드합니다 . 그러나 서버에서 무언가를 다운로드하면 Main Thread에서 다운로드 작업 업데이트 UI가 완료됩니다.
HomeModel.getPostings(completionHandler: {(response: Any) -> Void in
guard response as? String != "Failed" else {
//Code to send a pop-up alert to the user
return
}
self.jsonData = response as? [[String: Any]]
self.jsonCount = (self.jsonData?.count)!
DispatchQueue.main.async {
// Update UI on Main Thread
collectionView.reloadData()
}
})
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다