我想从家庭控制器中的youtube上检索数据,然后将我的数据传递给我的视频控制器,但是该数据并未传输到我的视频控制器中。但是当我尝试打印数据时,数据就在家庭控制器中。这是我的代码
这是我放在家庭控制器类之上的协议
protocol VideoListDelegate: class {
func didAddVideoItem(results: [SearchResult])
}
这是我的家庭控制器类中的实例委托
weak var delegate: VideoListDelegate?
这是我在家庭控制器中调用的api
private func youtubeAPI(with query: Method) {
let request = SearchListRequest(part: [.id, .snippet], maxResults: 50, searchQuery: query.rawValue)
ApiSession.shared.send(request) { (results) in
if let err = results.error {
print(" -- Failed to get data -- ")
print(" -- \(err) -- ")
return
}
if let result = results.value?.items {
self.delegate?.didAddVideoItem(results: result)
}
let layout = UICollectionViewFlowLayout()
let searchVideoController = VideoController(collectionViewLayout: layout)
self.navigationController?.pushViewController(searchVideoController, animated: true)
}
}
然后我使视频控制器符合协议
class VideoController: UICollectionViewController, UICollectionViewDelegateFlowLayout, VideoListDelegate {
// Add video into video array
func didAddVideoItem(results: [SearchResult]) {
for item in results {
print(item.snippet.title)
let video = Video(title: item.snippet.title, videoId: item.id.videoID ?? "")
self.videos.append(video)
}
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
}
答案 0 :(得分:0)
您的API方法应该是这样,那么您就不需要委派来传递数据:
private func youtubeAPI(with query: Method) {
let request = SearchListRequest(part: [.id, .snippet], maxResults: 50, searchQuery: query.rawValue)
ApiSession.shared.send(request) { (results) in
if let err = results.error {
print(" -- Failed to get data -- ")
print(" -- \(err) -- ")
return
}
let layout = UICollectionViewFlowLayout()
let searchVideoController = VideoController(collectionViewLayout: layout)
searchVideoController.results = results.value?.items ?? []
self.navigationController?.pushViewController(searchVideoController, animated: true)
}
}
然后在您的VideoViewController中添加一个类型为results
的变量[SearchResult]
。