Swift 3解析youtube视频不会显示结果并继续加载 - IOS 10

时间:2016-12-10 00:57:37

标签: ios swift swift3 ios10

我正在尝试通过json解析来获取youtube频道和视频,而我是Swift 3的新手。但是,加载图标不会消失,也不会显示任何结果,日志中没有错误。< / p>

这是我的代码:

1 / func getVideosForChannelAtIndex:

func getVideosForChannelAtIndex(_ index: Int!) {

    let playlistID = channelsDataArray[index]["playlistID"] as! String
    let urlString = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=\(playlistID)&key=\(apiKey)"
    let targetURL = URL(string: urlString)
    var url = URLRequest(url: targetURL!)
    url.httpMethod = "GET"
    URLSession.shared.dataTask(with: url) { (data, response, error) in
        let httpStatus = response as? HTTPURLResponse

        if httpStatus!.statusCode == 200 && error != nil {



            do {
                let resultsDict = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! Dictionary<String, AnyObject>

                let items: Array<Dictionary<String, AnyObject>> = resultsDict["items"] as! Array<Dictionary<String, AnyObject>>

                for i in 0 ..< items.count {
                    let playlistSnippetDict = (items[i] as Dictionary<String, AnyObject>)["snippet"] as! Dictionary<String, AnyObject>

                    var desiredPlaylistItemDataDict = Dictionary<String, AnyObject>()

                    desiredPlaylistItemDataDict["title"] = playlistSnippetDict["title"]
                    desiredPlaylistItemDataDict["thumbnail"] = ((playlistSnippetDict["thumbnails"] as! Dictionary<String, AnyObject>)["default"] as! Dictionary<String, AnyObject>)["url"]
                    desiredPlaylistItemDataDict["videoID"] = (playlistSnippetDict["resourceId"] as! Dictionary<String, AnyObject>)["videoId"]

                    self.videosArray.append(desiredPlaylistItemDataDict)

                    self.tableView.reloadData()
                }
            } catch {
                print(error)
            }
        }
        else {
            print("Error while loading channel videos: \(error)")
        }

        self.activityView.isHidden = true
    }



        }

2 / func getChannelDetails:

func getChannelDetails(_ useChannelIDParam: Bool) {

    var urlString: String!

    if !useChannelIDParam {
        urlString = "https://www.googleapis.com/youtube/v3/channels?part=contentDetails,snippet&forUsername=\(desiredChannelsArray[channelIndex])&key=\(apiKey)"
    }
    else {
        urlString = "https://www.googleapis.com/youtube/v3/channels?part=contentDetails,snippet&id=\(desiredChannelsArray[channelIndex])&key=\(apiKey)"
    }

    let targetURL = URL(string: urlString)
    var request = URLRequest(url: targetURL!)
    request.httpMethod = "GET"
    URLSession.shared.dataTask(with: request) { (data, response, error) in
        let httpStatus = response as? HTTPURLResponse

        if httpStatus!.statusCode == 200 && error != nil {



            do {
                let resultsDict = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! Dictionary<String, AnyObject>

                let items: AnyObject! = resultsDict["items"] as AnyObject!
                let firstItemDict = (items as! Array<AnyObject>)[0] as! Dictionary<String, AnyObject>

                let snippetDict = firstItemDict["snippet"] as! Dictionary<String, AnyObject>

                var desiredValuesDict: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>()
                desiredValuesDict["title"] = snippetDict["title"]
                desiredValuesDict["description"] = snippetDict["description"]
                desiredValuesDict["thumbnail"] = ((snippetDict["thumbnails"] as! Dictionary<String, AnyObject>)["default"] as! Dictionary<String, AnyObject>)["url"]

                desiredValuesDict["playlistID"] = ((firstItemDict["contentDetails"] as! Dictionary<String, AnyObject>)["relatedPlaylists"] as! Dictionary<String, AnyObject>)["uploads"]


                self.channelsDataArray.append(desiredValuesDict)


                self.tableView.reloadData()

                self.channelIndex += 1
                if self.channelIndex < self.desiredChannelsArray.count {
                    self.getChannelDetails(useChannelIDParam)
                }
                else {
                    self.activityView.isHidden = true
                }
            } catch {
                print(error)
            }

        } else {
            print("Error while loading channel details: \(error)")
        }
    }



    }


    }

3 / func textFieldShouldReturn:

func textFieldShouldReturn(_ textField: UITextField) -> Bool {

    textField.resignFirstResponder()
    activityView.isHidden = false

    var type = "channel"
    if segmentDisplay.selectedSegmentIndex == 1 {

    type = "video"
        videosArray.removeAll(keepingCapacity: false)

    }
    var urlString = "https://www.googleapis.com/youtube/v3/search?part=snippet&q=\(textField.text)&type=\(type)&key=\(apiKey)"

    urlString = urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!



    let targetURL = URL(string: urlString)

    var request = URLRequest(url: targetURL!)
    request.httpMethod = "GET"

URLSession.shared.dataTask(with: request) { (data, response, error) in
let httpStatus = response as? HTTPURLResponse
if httpStatus!.statusCode == 200 && error != nil {


    do {
        let resultsDict = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! Dictionary<String, AnyObject>

        let items: Array<Dictionary<String, AnyObject>> = resultsDict["items"] as! Array<Dictionary<String, AnyObject>>

        for i in 0 ..< items.count {
            let snippetDict = items[i]["snippet"] as! Dictionary<String, AnyObject>

            if self.segmentDisplay.selectedSegmentIndex == 0 {
                self.desiredChannelsArray.append(snippetDict["channelId"] as! String)
            }
            else {
                var videoDetailsDict = Dictionary<String, AnyObject>()
                videoDetailsDict["title"] = snippetDict["title"]
                videoDetailsDict["thumbnail"] = ((snippetDict["thumbnails"] as! Dictionary<String, AnyObject>)["default"] as! Dictionary<String, AnyObject>)["url"]
                videoDetailsDict["videoID"] = (items[i]["id"] as! Dictionary<String, AnyObject>)["videoId"]

                self.videosArray.append(videoDetailsDict)

                self.tableView.reloadData()
            }
        }
    } catch {
        print(error)
    }

    if self.segmentDisplay.selectedSegmentIndex == 0 {
        self.getChannelDetails(true)
    }

}
else {
    print("Error while loading channel videos: \(error)")
}

self.activityView.isHidden = true
    }


    return true


}

1 个答案:

答案 0 :(得分:0)

正如评论中所提到的,您必须在每项任务上调用resume(),因为URLSession的所有任务都会被默认暂停。

以这种方式使用你的单行:

URLSession.shared.dataTask(with: request) { (data, response, error) in

  ...

}.resume()

可选地

let task = URLSession.shared.dataTask(with: request) { (data, response, error) in

  ...

}
task.resume()

顺便说一下,根本不需要URLRequest个实例。 GET是默认的HTTP方法。

注意:确保包含字符串插值的URL中嵌入的所有可选值都已解包,否则您将获得文字Optional("Foo")字符串。例如,第三个代码段中的textField.text绝对是可选的。