let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
if error != nil {
println("error=\(error)")
return
}
在这段代码中,我的PHP连接出现dataTaskWithRequest(request)
错误。它在迁移到Swift 2之前有效。
答案 0 :(得分:1)
这是正确的语法:
let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: {(data, response, error) in
// your code
})
来自this的示例代码回答:
var url : NSURL = NSURL(string: "https://itunes.apple.com/search?term=\(searchTerm)&media=software")
var request: NSURLRequest = NSURLRequest(URL: url)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let task : NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
// notice that I can omit the types of data, response and error
// your code
});
// do whatever you need with the task
<强>更新强>
let url : NSURL = NSURL(string: "https://itunes.apple.com/search?term=&media=software")!
let request: NSURLRequest = NSURLRequest(URL: url)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let task : NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
do {
let JSON = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions(rawValue: 0))
guard let JSONDictionary :NSDictionary = JSON as? NSDictionary else {
print("Not a Dictionary")
//get your JSONData here from dictionary.
return
}
print("JSONDictionary! \(JSONDictionary)")
}
catch let JSONError as NSError {
print("\(JSONError)")
}
})