0

我是 swift 和 ios 编程的新手,我有以下代码块查询一些歌曲的 url,我应该取回歌曲。

    let defaultSession = URLSession(configuration: URLSessionConfiguration.default)

    var dataTask: URLSessionDataTask?            

    if dataTask != nil {
        dataTask?.cancel()
    }


    let expectedCharSet = CharacterSet.urlQueryAllowed
    let searchTerm      = term.addingPercentEncoding(withAllowedCharacters: expectedCharSet)!
    let url = URL(string: "https://itunes.apple.com/search?media=music&entity=song&term=\(term)")

    print("URL: ", url)

    // building up a dataTask computation
    dataTask = defaultSession.dataTask( with: url!)

        {(maybe_data, response, error) in 

                    if error != nil {

                        print("Error: ", error!.localizedDescription)
                        // closure(nil)
                        return

                    } else if let httpResponse = response as? HTTPURLResponse {

                        print("no error")

                        if httpResponse.statusCode == 200 {

                            if let data = maybe_data {

                                // closure(songData)
                                print("songData: ", data)

                            } else {

                                print("no song data")
                                return 
                            }
                        }
                    }

                  }

    // does htis run the data task? is it a promise that's build?
    dataTask?.resume()

问题是我想从完成处理程序中获取数据,所以理想情况下我会写

let music = dataTask?.resume()

但是,我不确定如何输出该值。

4

0 回答 0