gpt4 book ai didi

swift 。为什么 dataTaskWithRequest 不调用闭包?

转载 作者:搜寻专家 更新时间:2023-11-01 05:38:59 24 4
gpt4 key购买 nike

这是我的代码:

let targetURL = NSURL(string: self.urlStringForRequestChannelDetails)
let request = NSMutableURLRequest(URL: targetURL!)
request.HTTPMethod = "GET"
let defSession = NSURLSession.sharedSession()
let task = defSession.dataTaskWithRequest(request, completionHandler: { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
let HTTPStatusCode = (response as! NSHTTPURLResponse).statusCode
if HTTPStatusCode == 200 && error == nil {
var resultsDict = [NSObject:AnyObject]()
do {
resultsDict = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! [NSObject:AnyObject]
} catch let caught as NSError {
print(caught.description)
}
let items = resultsDict["items"] as! [AnyObject]
let firstItemDict = items[0] as! [NSObject:AnyObject]

let snippetDict = firstItemDict["snippet"] as! [NSObject:AnyObject]
self.channelData["title"] = snippetDict["title"]
self.channelData["description"] = snippetDict["description"]

self.channelData["thumbnail"] = ((snippetDict["thumbnails"] as! [NSObject:AnyObject])["default"] as! [NSObject:AnyObject])["url"]
self.channelData["playlistId"] = ((firstItemDict["contentDetails"] as! [NSObject:AnyObject])["relatedPlaylists"] as! [NSObject:AnyObject])["uploads"]
} else {
print("HTTP Status Code = \(HTTPStatusCode)")
print("Error while loading channel details: \(error)")
}

})
task.resume()

我无法通过 brakepoint 在处理程序中停止执行,因为没有调用闭包。我做错了什么?


更新#1:

import Foundation

class YtDataManager {
static var shared_instance = YtDataManager()



let apiKey = "#################################"
let #########ChannelName = "#########"
var channelData = [NSObject:AnyObject]()
var videosArray = [[NSObject:AnyObject]]()

var playlistId: String { return self.channelData["playlistId"] as! String}
var urlStringForRequestChannelDetails: String { return String("https://www.googleapis.com/youtube/v3/channels?part=contentDetails,snippet&forUsername=\(self.#########ChannelName)&key=\(self.apiKey)") }
var urlStringForRequestChannelVideos: String { return String("https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=\(self.playlistId)&key=\(self.apiKey)") }


func performGetRequest(targetURL: NSURL!, completion: (data: NSData?, HTTPStatusCode: Int, error: NSError?) -> Void) {
}

func get###ChannelDetails() {
let targetURL = NSURL(string: self.urlStringForRequestChannelDetails)
let request = NSMutableURLRequest(URL: targetURL!)
request.HTTPMethod = "GET"
let defSession = NSURLSession.sharedSession()
let task = defSession.dataTaskWithRequest(request, completionHandler: { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in

let HTTPStatusCode = (response as! NSHTTPURLResponse).statusCode
if HTTPStatusCode == 200 && error == nil {
var resultsDict = [NSObject:AnyObject]()
do {
resultsDict = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! [NSObject:AnyObject]
} catch let caught as NSError {
print(caught.description)
}
let items = resultsDict["items"] as! [AnyObject]
let firstItemDict = items[0] as! [NSObject:AnyObject]

let snippetDict = firstItemDict["snippet"] as! [NSObject:AnyObject]
self.channelData["title"] = snippetDict["title"]
self.channelData["description"] = snippetDict["description"]

self.channelData["thumbnail"] = ((snippetDict["thumbnails"] as! [NSObject:AnyObject])["default"] as! [NSObject:AnyObject])["url"]
self.channelData["playlistId"] = ((firstItemDict["contentDetails"] as! [NSObject:AnyObject])["relatedPlaylists"] as! [NSObject:AnyObject])["uploads"]
} else {
print("HTTP Status Code = \(HTTPStatusCode)")
print("Error while loading channel details: \(error)")
}

})
task.resume()


}


func getVideosFor###Channel() {
let targetURL = NSURL(fileURLWithPath: self.urlStringForRequestChannelVideos)
self.performGetRequest(targetURL, completion: { (data, HTTPStatusCode, error) -> Void in
if HTTPStatusCode == 200 && error == nil {
var resultsDict = [NSObject:AnyObject]()
do {
resultsDict = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! [NSObject:AnyObject]
} catch let caught as NSError {
print(caught.description)
}
let items: Array<Dictionary<NSObject, AnyObject>> = resultsDict["items"] as! Array<Dictionary<NSObject, AnyObject>>

// Use a loop to go through all video items.
for var i=0; i<items.count; ++i {
let playlistSnippetDict = (items[i] as Dictionary<NSObject, AnyObject>)["snippet"] as! Dictionary<NSObject, AnyObject>

// Initialize a new dictionary and store the data of interest.
var desiredPlaylistItemDataDict = Dictionary<NSObject, AnyObject>()

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

// Append the desiredPlaylistItemDataDict dictionary to the videos array.
self.videosArray.append(desiredPlaylistItemDataDict)

// Reload the tableview.
//self.tblVideos.reloadData()
}
} else {
print("HTTP Status Code = \(HTTPStatusCode)")
print("Error while loading channel videos: \(error)")
}
})
}
}

请不要介意空函数。因为我已经开始变通,所以我试图让代码更简单。


更新#2:

import UIKit

class YtFeedViewController: UIViewController {
@IBOutlet weak var menuButton:UIBarButtonItem!

override func viewDidLoad() {
super.viewDidLoad()

if self.revealViewController() != nil {
menuButton.target = self.revealViewController()
menuButton.action = "revealToggle:"
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())

YtDataManager.shared_instance.get###ChannelDetails()
print(YtDataManager.shared_instance.channelData.count) //0!
YtDataManager.shared_instance.getVideosFor###Channel()
}

self.navigationItem.title = "YouTube feed"
// Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

最佳答案

其实是这样的。我只是复制并粘贴您的代码,删除自定义逻辑并运行它。

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()

let targetURL = NSURL(string: "https://google.com")
let request = NSMutableURLRequest(URL: targetURL!)
request.HTTPMethod = "GET"
let defSession = NSURLSession.sharedSession()
let task = defSession.dataTaskWithRequest(request, completionHandler: { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
print(response)

})
task.resume()
}
}

enter image description here

关于 swift 。为什么 dataTaskWithRequest 不调用闭包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33131824/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com