2016-05-16 110 views
-2

我做了一個簡單的GET請求與NSURLRequest, 下面的代碼:錯誤的NSURLRequest,無法識別的選擇發送到實例

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:完成:]:無法識別的選擇發送到實例0x7f93d1714270

+3

使用讓會話= NSURLSession.sharedSession() –

+0

良好的漁獲@AnkitaShah – Lion

回答

0

您應該參加共享會話而不是創建新會話

let session = NSURLSession.sharedSession() 

或者你也可以創建自己的會話,但你必須提供會話配置成構造

let config = NSURLSessionConfiguration.defaultSessionConfiguration() 
let session = NSURLSession(configuration: config) 
相關問題