gpt4 book ai didi

ios - 为什么函数不检索数据?

转载 作者:行者123 更新时间:2023-11-28 06:56:12 25 4
gpt4 key购买 nike

我正在尝试从 iTunes 搜索 API 获取预览链接。我有一个函数可以在单击按钮时获取信息,但没有调用该函数。我想获取结果数组中第一个对象的预览链接 我该如何解决这个问题? enter image description here

var d: NSMutableData = NSMutable Data()

var tData: NSArray = NSArray()

func ctn(receivedResponse: NSURLConnection!, receivedResponse response: NSURLResponse!) {
// clear out the data object if a new request was received.
self.d = NSMutableData()
}

func ctn(ctn: NSURLConnection!, receivedData d: NSData!) {
self.d.appendData(d)
}
func ctnFinishedLoading(ctn: NSURLConnection!) throws {
var err: NSError
var jResult: NSDictionary = try NSJSONSerialization.JSONObjectWithData(d, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
if jResult.count>0 && jResult["results"]!.count>0 {
var results: NSArray = jResult["results"]as! NSArray
self.tData = results
print(tData)
//self.appsTableView.reloadData()
}

}


func playit(sender: UIButton!) {



let cell = table.dequeueReusableCellWithIdentifier("cell")

let playButtonrow = sender.tag

print(ret[playButtonrow])

let searchTerm: String = ret[playButtonrow]

let itunesSearchTerm = searchTerm.stringByReplacingOccurrencesOfString(" ", withString: "+", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil)

if let escapedSearchTerm = itunesSearchTerm.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) {
let urlPath = "https://itunes.apple.com/search?term=\(escapedSearchTerm)&media=music"
let url: NSURL = NSURL(string: urlPath)!
let request: NSURLRequest = NSURLRequest(URL: url)
let ctn: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)!


print("Search iTunes API at URL \(url)")

ctn.start()



}

最佳答案

获取 previewUrl 的方法是获取单个结果数组成员的值,例如第一个索引为 0 的成员,然后提取 previewUrl 键的值。例如:

if jResult.count>0 && jResult["results"]!.count>0 {
var results: NSArray = jResult["results"]as! NSArray

if let previewUrl = results[0]["previewUrl"] {
print(previewUrl!)
}
}

由于 NSURLConnection 在 iOS 9 中被弃用,我还将为您提供一种使用 NSURLSession 从 iTunes API 检索 previewUrls 的方法。

let urlPath = "https://itunes.apple.com/search?term=\(escapedSearchTerm)&media=music"
let url: NSURL = NSURL(string: urlPath)!
let task = NSURLSession.sharedSession().dataTaskWithURL(url) {(data, response, error) -> Void in
do {
if let dict: NSDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
{
// The search is complete.
for result in dict["results"] as! NSArray {
if let previewUrl = result["previewUrl"] {
print(previewUrl!)
}
}
}
} catch let jsonError as NSError {
// Handle error.
}
}
task.resume()

关于ios - 为什么函数不检索数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33578565/

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