我有一些代码,我用了一段时间,运行得很好。 我现在希望在我的新项目中使用它,该项目是 swift 3,虽然我已经修复了大多数错误,但我仍然有两个如下:
以下代码行:var _: NSData? = NSURLConnection.sendSynchronousRequest(request as URLRequest, returning:&response) as NSData
产生以下错误:Call can throw, but it is not marked with 'try' and the error is not handled
以下代码行:NSLog("Response code: %ld", res?.statusCode ?? <#default value#>);
生成以下错误:Editor placeholder in source file
。
任何帮助,不胜感激。
以下是可能有助于解决问题的完整代码:
func webViewDidFinishLoad(_ webView: UIWebView) {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
let post:NSString = "userid=349&devicetoken=walan"
NSLog("PostData: %@",post);
let url:NSURL = NSURL(string: "https://str8red.com/updateAPN")!
let postData:NSData = post.data(using: String.Encoding.ascii.rawValue)! as NSData
let postLength:NSString = String( postData.length ) as NSString
let request:NSMutableURLRequest = NSMutableURLRequest(url: url as URL)
request.httpMethod = "POST"
request.httpBody = postData as Data
request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
var _: NSError?
var response: URLResponse?
var _: NSData? = NSURLConnection.sendSynchronousRequest(request as URLRequest, returning:&response) as NSData
let res = response as! HTTPURLResponse!;
NSLog("Response code: %ld", res?.statusCode ?? <#default value#>);
}
您可以添加try关键字,并用do {} catch {}将语句括起来,如下所示:
do {
try NSURLConnection.sendSynchronousRequest(request as URLRequest, returning:&response) as NSData
} catch {
print(error)
}
自iOS 9以来,您仍然会收到有关该功能已弃用的警告。
我将尝试查看如何在iOS 10,Swift 3.1语法中重写整个函数,但是存在它可能会损坏并且看起来与其他遗留代码非常不同的危险。 敬请期待,我会再次更新这个答案。
至于"占位符错误",您可以输入一些值,例如"500",默认为"内部服务器错误"
NSLog("Response code: %ld", res?.statusCode ?? 500);
更新:这是更新到 Swift 3、iOS 10 的功能。
我只根据函数的原始意图进行更新。只是语法/API更新,没有删除/添加任何功能。
func webViewDidFinishLoad(_ webView: UIWebView) {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
let post:String = "userid=349&devicetoken=walan"
NSLog("PostData: %@",post);
let url:URL = URL(string: "https://str8red.com/updateAPN")!
let postData:Data = post.data(using: String.Encoding(rawValue: String.Encoding.ascii.rawValue))!
let postLength: String = String( postData.count )
var request:URLRequest = URLRequest(url: url as URL)
request.httpMethod = "POST"
request.httpBody = postData as Data
request.setValue(postLength, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
var _: NSError?
var response: URLResponse?
URLSession.shared.dataTask(with: request) { (data, res, error) in
guard error == nil else {
print(error!)
return
}
response = res
}
let res = response as! HTTPURLResponse!;
NSLog("Response code: %ld", res?.statusCode ?? 500);
}