Swift 致命错误:使用URLSession展开可选值时意外发现nil
我有一个在Swift 2.2中使用的方法,但自从我将代码转换为Swift 3后,它就不再工作了,这个方法所做的是使用Windows身份验证将用户名和密码登录到URL中,如果凭据正确,它将返回true,如果它们不正确,它将返回false 方法如下:Swift 致命错误:使用URLSession展开可选值时意外发现nil,swift,swift3,Swift,Swift3,我有一个在Swift 2.2中使用的方法,但自从我将代码转换为Swift 3后,它就不再工作了,这个方法所做的是使用Windows身份验证将用户名和密码登录到URL中,如果凭据正确,它将返回true,如果它们不正确,它将返回false 方法如下: func loginUser(_ username: String, password: String, completion: @escaping (_ result: Bool) -> Void) { //Setup
func loginUser(_ username: String, password: String, completion: @escaping (_ result: Bool) -> Void)
{
//Setup the NSURLSessionConfiguration
let configuration = URLSessionConfiguration.default
//Setup the NSURLSession
let session = Foundation.URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
//Add the username and password to NSURLCredential
credential = URLCredential(user:username, password:password, persistence: .forSession)
//Create request URL as String
let requestString = NSString(format:"%@", webservice) as String
//Convert URL string to NSURL
let url: URL! = URL(string: requestString)
//Prepare the task to get data.
let task = session.dataTask(with: url, completionHandler: {
data, response, error in
DispatchQueue.main.async(execute: {
if(error == nil)
{
//If there is no error calling the API, return true
completion(true)
}
else
{
//If there is an error calling the API, return false
completion(false)
}
})
})
//Run the task to get data.
task.resume()
}
我得到了这个错误:
fatal error: unexpectedly found nil while unwrapping an Optional value
这就发生在这里:
let task = session.dataTask(with: url, completionHandler: {
data, response, error in
DispatchQueue.main.async(execute: {
if(error == nil)
{
//If there is no error calling the API, return true
completion(true)
}
else
{
//If there is an error calling the API, return false
completion(false)
}
})
})
我做错了什么
这将出现在“我的调试导航器”中的致命错误之前:
function signature specialization <preserving fragile attribute, Arg[1] = [Closure Propagated : reabstraction thunk helper from @callee_owned (@unowned Swift.UnsafeBufferPointer<Swift.UInt8>) -> () to @callee_owned (@unowned Swift.UnsafeBufferPointer<Swift.UInt8>) -> (@out ()), Argument Types : [@callee_owned (@unowned Swift.UnsafeBufferPointer<Swift.UInt8>) -> ()]> of generic specialization <preserving fragile attribute, ()> of Swift.StaticString.withUTF8Buffer <A> ((Swift.UnsafeBufferPointer<Swift.UInt8>) -> A) -> A
它不喜欢这些方法。将URL声明从
let url: URL! = URL(string: requestString)
致:
只有这样才能解决问题;或者它将显示您的
请求字符串
不正确。将URL声明从
let url: URL! = URL(string: requestString)
致:
只有这样才能解决问题;或者它将显示您的
请求字符串不正确。此答案适用于有此问题的人,但方式不同。
以下是我面临和解决的问题:
我有一个搜索字段,可以在tableview中查看一些结果。
它会以数字方式崩溃,或者删除单词,并尽可能快地进行数字化。
我设置了一个异常断点,但没有显示崩溃的位置。所以a回到了踏板上,从这开始:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "iTableViewCell", for: indexPath) as! MyClassTableViewCell
cell.setCellFood(with: self.elementsArray[indexPath.row]) // <-- HERE
return cell
}
func tableView(tableView:UITableView,cellForRowAt indexath:indexPath)->UITableViewCell{
让cell=tableView.dequeueReusableCell(标识符为:“iTableViewCell”,用于:indexath)作为!MyClassTableViewCell
cell.setCellFood(带:self.elementsArray[indexPath.row])//Bool{
self.elementsArray.removeAll()//3{
let predicate=NSPredicate(格式:“status='A',name包含[cd]%@”,textField.text!)
let filtered=MyObjectRealm().get(withFilter:,谓词:nil,nsPredicate:谓词)
过滤。forEach({(食物)在
self.elementsArray.append(食物)
self.reloadAllDataCustom()
})
}否则{
self.elementsArray=MyObjectRealm().get(带筛选器:“状态='A'”)
self.reloadAllDataCustom()
}
}
返回真值
}
因此,当它删除所有元素时,它会崩溃
问题在于DispatchQueue.main.asyncAfter(截止日期:.now())
它的延迟时间为.now()+0.2
,然后,它没有时间再次重新加载元素,导致崩溃
现在它是实时擦除和填充的,并且永远不会再次崩溃,因为它在填充单元格时永远不会返回nil。
希望能帮助别人去发现错误 此答案适用于有此问题但方式不同的人。
以下是我面临和解决的问题:
我有一个搜索字段,可以在tableview中查看一些结果。
它会以数字方式崩溃,或者删除单词,并尽可能快地进行数字化。
我设置了一个异常断点,但没有显示崩溃的位置。所以a回到了踏板上,从这开始:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "iTableViewCell", for: indexPath) as! MyClassTableViewCell
cell.setCellFood(with: self.elementsArray[indexPath.row]) // <-- HERE
return cell
}
func tableView(tableView:UITableView,cellForRowAt indexath:indexPath)->UITableViewCell{
让cell=tableView.dequeueReusableCell(标识符为:“iTableViewCell”,用于:indexath)作为!MyClassTableViewCell
cell.setCellFood(带:self.elementsArray[indexPath.row])//Bool{
self.elementsArray.removeAll()//3{
let predicate=NSPredicate(格式:“status='A',name包含[cd]%@”,textField.text!)
let filtered=MyObjectRealm().get(withFilter:,谓词:nil,nsPredicate:谓词)
过滤。forEach({(食物)在
self.elementsArray.append(食物)
self.reloadAllDataCustom()
})
}否则{
self.elementsArray=MyObjectRealm().get(带筛选器:“状态='A'”)
self.reloadAllDataCustom()
}
}
返回真值
}
因此,当它删除所有元素时,它会崩溃
问题在于DispatchQueue.main.asyncAfter(截止日期:.now())
它的延迟时间为.now()+0.2
,然后,它没有时间再次重新加载元素,导致崩溃
现在它是实时擦除和填充的,并且永远不会再次崩溃,因为它在填充单元格时永远不会返回nil。
希望能帮助别人去发现错误 请举例说明,如果有效,我将接受您的回答。url
可能为零。requestString
的值是多少?url与requestString不同,它不是零。它是有效的url吗?是的,我在浏览器示例中尝试过。如果它有效,我将接受您的答案。url
可能是零。requestString
的值是多少?url与requestString不为零,不是为零。它是有效的url吗?是的,我在浏览器中尝试过
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
self.elementsArray.removeAll() // <-- Last thing debbuging i found stop here
DispatchQueue.main.asyncAfter(deadline: .now()) {
if textField == self.txtSearch && (textField.text?.characters.count)! > 3 {
let predicate = NSPredicate(format: "status = 'A' AND name CONTAINS [cd] %@", textField.text!)
let filtered = MyObjectRealm().get(withFilter: "", predicate: nil, nsPredicate: predicate)
filtered.forEach({ (food) in
self.elementsArray.append(food)
self.reloadAllDataCustom()
})
}else{
self.elementsArray = MyObjectRealm().get(withFilter: "status = 'A'")
self.reloadAllDataCustom()
}
}
return true
}