【问题标题】:Error in NSURLRequest, unrecognized selector sent to instanceNSURLRequest 出错,无法识别的选择器发送到实例
【发布时间】:2016-05-16 10:48:32
【问题描述】:

我用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

【问题讨论】:

  • 使用 let session = NSURLSession.sharedSession()
  • 好收获@AnkitaShah

标签: ios swift alamofire


【解决方案1】:

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

let session = NSURLSession.sharedSession()

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-04
    • 1970-01-01
    • 2019-08-28
    • 2012-07-24
    相关资源
    最近更新 更多