sendAsynchronousRequest在iOS 9中被弃用,如何更改代码以修复
下面是我遇到问题的代码:sendAsynchronousRequest在iOS 9中被弃用,如何更改代码以修复,ios,swift,ios9,Ios,Swift,Ios9,下面是我遇到问题的代码: func parseFeedForRequest(request: NSURLRequest, callback: (feed: RSSFeed?, error: NSError?) -> Void) { NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response, data, error) -> Void in
func parseFeedForRequest(request: NSURLRequest, callback: (feed: RSSFeed?, error: NSError?) -> Void)
{
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response, data, error) -> Void in
if ((error) != nil)
{
callback(feed: nil, error: error)
}
else
{
self.callbackClosure = callback
let parser : NSXMLParser = NSXMLParser(data: data!)
parser.delegate = self
parser.shouldResolveExternalEntities = false
parser.parse()
}
}
}
从iOS 9开始,它就不再推荐了,它告诉我改为使用dataTaskWithRequest。有人能帮我用dataTask更改sendAsync吗,我不知道怎么做。使用
NSURLSession
,而不是像下面这样
目标C
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:"YOUR URL"]
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
// handle response
}] resume];
对于斯威夫特
var request = NSMutableURLRequest(URL: NSURL(string: "YOUR URL")!)
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
var params = ["username":"username", "password":"password"] as Dictionary<String, String>
request.HTTPBody = try? NSJSONSerialization.dataWithJSONObject(params, options: [])
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
print("Response: \(response)")})
task.resume()
var-request=NSMutableURLRequest(URL:NSURL(字符串:“您的URL”)!)
var session=NSURLSession.sharedSession()
request.HTTPMethod=“POST”
var params=[“用户名”:“用户名”,“密码”:“密码”]作为字典
request.HTTPBody=try?NSJSONSerialization.dataWithJSONObject(参数,选项:[])
request.addValue(“应用程序/json”,forHTTPHeaderField:“内容类型”)
request.addValue(“application/json”,forHTTPHeaderField:“Accept”)
var task=session.dataTaskWithRequest(请求,completionHandler:{data,response,error->Void in
打印(“响应:\(响应)”)}
task.resume()
对于异步查询,来自Apple
与大多数网络API一样,NSURLSession API具有高度的灵活性
异步的。它以两种方式之一返回数据,具体取决于
您调用的方法:
到一个完成处理程序块,当
传输成功完成或出现错误
通过在接收数据时对自定义委托调用方法
在下载到文件时调用自定义委托上的方法
完成
迅速实施
let session = NSURLSession.sharedSession()
session.dataTaskWithRequest(request) { (data, response, error) -> Void in
}
这是swift 2.1版本:
let request = NSMutableURLRequest(URL: NSURL(string: "YOUR URL")!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
let params = ["username":"username", "password":"password"] as Dictionary<String, String>
request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: [])
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
print("Response: \(response)")})
task.resume()
let request=NSMutableURLRequest(URL:NSURL(字符串:“您的URL”)!)
let session=NSURLSession.sharedSession()
request.HTTPMethod=“POST”
让params=[“用户名”:“用户名”,“密码”:“密码”]作为字典
request.HTTPBody=试试看!NSJSONSerialization.dataWithJSONObject(参数,选项:[])
request.addValue(“应用程序/json”,forHTTPHeaderField:“内容类型”)
request.addValue(“application/json”,forHTTPHeaderField:“Accept”)
让task=session.dataTaskWithRequest(请求,completionHandler:{data,response,error->Void in
打印(“响应:\(响应)”)}
task.resume()
用一个例子说明了反对使用以下代码的替代代码:
sendAsynchronousRequest(quot:queue:completionHandler:)”在iOS 9.0中被弃用:使用[NSURLSession dataTaskWithRequest:completionHandler:]
在Swift 2.1及以后的版本中进行测试和工作
import UIKit
class ViewController: UIViewController {
@IBOutlet var theImage: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL(string: "https://upload.wikimedia.org/wikipedia/commons/6/6a/Johann_Sebastian_Bach.jpg")
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, response, error) -> Void in
if error != nil {
print("thers an error in the log")
} else {
dispatch_async(dispatch_get_main_queue()) {
let image = UIImage(data: data!)
self.theImage.image = image
}
}
}
task.resume()
}
}
//在ViewControllers ImageView上显示图像。连接ImageView的插座Swift 2.0: 旧的(以下替换为新的): 新的: Swift 3.0
var request = URLRequest(url: URL(string: "http://example.com")!)
request.httpMethod = "POST"
let session = URLSession.shared
session.dataTask(with: request) {data, response, err in
print("Entered the completionHandler")
}.resume()
以下是具有JSONSerialised数据的SWIFT3.0版本
let url = URL(string: "<HERE GOES SERVER API>")!
var request = URLRequest(url: url)
request.httpMethod = "POST" //GET OR DELETE etc....
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("<ValueforAuthorization>", forHTTPHeaderField: "Authorization")
let parameter = [String:Any]() //This is your parameters [String:Any]
do {
let jsonData = try JSONSerialization.data(withJSONObject: parameter, options: .prettyPrinted)
// here "jsonData" is the dictionary encoded in JSON data
request.httpBody = jsonData
let session = URLSession(configuration: .default)
let task = session.dataTask(with: request, completionHandler: { (incomingData, response, error) in
if let error = error {
print(error.localizedDescription)
print(request)
}else if let response = response {
print(response)
}else if let incomingData = incomingData {
print(incomingData)
}
})
task.resume()
} catch {
print(error.localizedDescription)
}
let url=url(字符串:“”)!
var-request=URLRequest(url:url)
request.httpMethod=“POST”//GET或DELETE等。。。。
request.setValue(“application/json”,forHTTPHeaderField:“Content Type”)
request.setValue(“,forHTTPHeaderField:“授权”)
让参数=[String:Any]()//这是您的参数[String:Any]
做{
让jsonData=try JSONSerialization.data(使用jsonObject:parameter,options:.prettypted)
//这里的“jsonData”是用JSON数据编码的字典
request.httpBody=jsonData
let session=URLSession(配置:。默认值)
让task=session.dataTask(带:request,completionHandler:{(incomingData,response,error))在
如果let error=error{
打印(错误。本地化描述)
打印(请求)
}否则,如果let response=response{
打印(答复)
}否则,如果让incomingData=incomingData{
打印(收入数据)
}
})
task.resume()
}抓住{
打印(错误。本地化描述)
}
使用swift 3.1
let request = NSMutableURLRequest(url: NSURL(string: image_url_string)! as URL)
let session = URLSession.shared
request.httpMethod = "POST"
let params = ["username":"username", "password":"password"] as Dictionary<String, String>
request.httpBody = try? JSONSerialization.data(withJSONObject: params, options: [])
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
print("Response: \(String(describing: response))")})
task.resume()
let request=NSMutableURLRequest(url:NSURL(string:image\u url\u string)!作为url)
让session=URLSession.shared
request.httpMethod=“POST”
让params=[“用户名”:“用户名”,“密码”:“密码”]作为字典
request.httpBody=try?JSONSerialization.data(带jsonObject:params,选项:[]))
request.addValue(“应用程序/json”,forHTTPHeaderField:“内容类型”)
request.addValue(“application/json”,forHTTPHeaderField:“Accept”)
让task=session.dataTask(其中:request作为URLRequest,completionHandler:{data,response,error->Void in
打印(“响应:\(字符串(描述:响应))”})
task.resume()
Swift 4
let params = ["email":"email@email.com", "password":"123456"] as Dictionary<String, String>
var request = URLRequest(url: URL(string: "http://localhost:8080/api/1/login")!)
request.httpMethod = "POST"
request.httpBody = try? JSONSerialization.data(withJSONObject: params, options: [])
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in
do {
let json = try JSONSerialization.jsonObject(with: data!) as! Dictionary<String, AnyObject>
print(json)
} catch {
print("error")
}
})
task.resume()
let params=[“电子邮件”:email@email.com“,”密码“:“123456”]作为字典
var request=URLRequest(url:url(字符串):http://localhost:8080/api/1/login")!)
request.httpMethod=“POST”
request.httpBody=try?JSONSerialization.data(带jsonObject:params,选项:[]))
request.addValue(“应用程序/json”,forHTTPHeaderField:“内容类型”)
让session=URLSession.shared
让task=session.dataTask(带:request,completionHandler:{data,response,error->Void in)
做{
让json=try JSONSerialization.jsonObject(使用:data!)作为!字典
打印(json)
}抓住{
打印(“错误”)
}
})
task.resume()
Swift 4.2
这对我很有用:
func loadImageFromURL(URL: NSURL) {
let request = URLRequest(url: URL as URL)
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let imageData = data {
DispatchQueue.main.async {
self.imageView.image = UIImage(data: imageData)
}
}
}
task.resume()
}
我不得不添加“DispatchQueue.main.async{}”,因为我有一个运行时警告,因为只有主线程应该修改UI元素。我认为NSURLConnection在iOS8中被弃用了。您应该从iOS7开始使用NSURLSession。有什么问题吗?您理解有困难吗?是的,我不知道如何将此转换为使用DataTaskWtihRequeust,我不知道需要更改什么。我同意DarkDust,NSURSession很容易理解。看看Ray的教程Patro
let params = ["email":"email@email.com", "password":"123456"] as Dictionary<String, String>
var request = URLRequest(url: URL(string: "http://localhost:8080/api/1/login")!)
request.httpMethod = "POST"
request.httpBody = try? JSONSerialization.data(withJSONObject: params, options: [])
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in
do {
let json = try JSONSerialization.jsonObject(with: data!) as! Dictionary<String, AnyObject>
print(json)
} catch {
print("error")
}
})
task.resume()
func loadImageFromURL(URL: NSURL) {
let request = URLRequest(url: URL as URL)
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let imageData = data {
DispatchQueue.main.async {
self.imageView.image = UIImage(data: imageData)
}
}
}
task.resume()
}