Xcode 二进制运算符!=无法应用于NSUrlConnection!类型的操作数!。类型与Nilliteral可转换
我是Swift的新手,我终于完成了我的第一个应用程序,但当更新发布时,我的代码完全搞糟了。。我的代码中的大多数错误是由调用中的Xcode 二进制运算符!=无法应用于NSUrlConnection!类型的操作数!。类型与Nilliteral可转换,xcode,swift,Xcode,Swift,我是Swift的新手,我终于完成了我的第一个应用程序,但当更新发布时,我的代码完全搞糟了。。我的代码中的大多数错误是由调用中的sendSynchronousRequestgiving额外参数“error”引起的。我试图改变它,最后想出了这个 var url = NSURL(string: "http://****") var request = NSMutableURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.
sendSynchronousRequest
giving额外参数“error”引起的。我试图改变它,最后想出了这个
var url = NSURL(string: "http://****")
var request = NSMutableURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReturnCacheDataElseLoad, timeoutInterval: Double.infinity);
if IJReachability.isConnectedToNetwork(){
request = NSMutableURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: Double.infinity);
}
var response: NSURLResponse?
let data = NSURLConnection!.self
do {
let data = try NSURLConnection.sendSynchronousRequest(request, returningResponse: &response)
} catch (let e) {
print(e)
}
if data != nil {
var dataArray = JSON(data: data)
let dutch_sentence = dataArray[id]["dutch_sentence"]
let polish_sentence = dataArray[id]["polish_sentence"]
let navigationTitle = dutch_sentence.string!.uppercaseString
self.title = navigationTitle
//Populate labels
dutchSentenceLabel.text = dutch_sentence.string!
polishSentenceLabel.text = polish_sentence.string!
}
但现在它说:
Binary operator != cannot be applied to operands of type NSUrlConnection!.Type and NilLiteralConvertible
对于行if数据!=nil{
考虑使用NSURLSessionTask而不是在iOS9中不推荐使用的NSUrlConnection
,例如:
var url = NSURL(string: "http://****")
var request = NSMutableURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReturnCacheDataElseLoad, timeoutInterval: Double.infinity);
if IJReachability.isConnectedToNetwork(){
request = NSMutableURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: Double.infinity);
}
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let task : NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
if data != nil {
var dataArray = JSON(data: data)
let dutch_sentence = dataArray[id]["dutch_sentence"]
let polish_sentence = dataArray[id]["polish_sentence"]
let navigationTitle = dutch_sentence.string!.uppercaseString
self.title = navigationTitle
//Populate labels
dutchSentenceLabel.text = dutch_sentence.string!
polishSentenceLabel.text = polish_sentence.string!
}
});
哦,谢谢你的工作,但是现在它在这一行给了我一个错误var-dataArray=JSON(data:data)
说不能用类型为(data:NSUrlConnection?)的参数列表调用类型为“JSON”的初始化器
我已经编辑了我的答案,sendSynchronousRequest
方法在iOS9中被弃用。你应该使用NSURLSessionDataTask
。还要检查你的JSON类构造函数。我在使用NSURLSessionDataTask
的地方问了一个新问题,但你能检查一下我的方法是否正确吗?