NSURLRequest出错,无法识别的选择器发送到实例

时间:2016-05-16 10:48:32

标签: ios swift alamofire

我用NSURLRequest做了一个简单的GET请求, 这是代码:

let todoEndpoint: String = "http://jsonplaceholder.typicode.com/todos/1"
    let url = NSURL(string: todoEndpoint)
    let urlRequest = NSURLRequest(URL: url!)
    let session = NSURLSession()

    let task = session.dataTaskWithRequest(urlRequest) {
        (data, response, error) in

        guard error == nil else {
            print("Error calling GET on /todos/1")
            print(error)
            return
        }

        guard let responseData = data else {
            print("Error: did not receive data")
            return
        }

    do {

        guard let todo = try NSJSONSerialization.JSONObjectWithData(responseData, options: []) as? [String: AnyObject] else {
            print("Error. ")
            return
        }

    print("The todo is " + todo.description)

        guard let todoTitle = todo["title"] as? String else {
            return
        }

    print("The title is " + todoTitle)

    } catch {
        return
    }
    }
    task.resume()

Xcode说:

[NSURLSession dataTaskForRequest:completion:]:无法识别的选择器发送到实例0x7f93d1714270

1 个答案:

答案 0 :(得分:0)

您应该使用共享会话而不是创建新会话

let session = NSURLSession.sharedSession()

或者您也可以创建自己的会话,但必须将会话配置提供给构造函数

let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)