从defaultSession完成处理程序获取数据

时间:2017-08-30 00:49:28

标签: ios swift urlsession

我是swift和ios编程的新手,我有以下代码块来查询某些歌曲的网址,我应该收回歌曲。

    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()

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

0 个答案:

没有答案