iOS Swift 3 POST问题
问题描述:
我有一些代码,我用了一段时间后,完美的工作。现在,我想在我的新项目,这是SWIFT 3使用它,虽然我有固定的大多数错误,我仍然有两人离开如下:iOS Swift 3 POST问题
下面的代码行: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 {}赶上{}声明如下:
do {
try NSURLConnection.sendSynchronousRequest(request as URLRequest, returning:&response) as NSData
} catch {
print(error)
}
你将仍然有一个警告,该功能已被弃用,因为iOS 9。
我会看看尝试看看整个功能如何可以重写在iOS 10,Swift 3.1语法,但有一个da说它可能会破坏,并且与其他遗留代码看起来会非常不同。敬请期待,我会再次更新这个答案。
至于“占位符错误”你可以把像“500”的一些值,例如默认为“内部服务器错误”
NSLog("Response code: %ld", res?.statusCode ?? 500);
更新:这里是更新到斯威夫特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);
}
如果您满意,请接受并回复它。如果您有其他问题,请发表评论。 – Wismin