2016-10-03 41 views
2

我有這個方法在Swift 2.2中工作,但自從我將代碼轉換爲Swift 3後,它不再有效,此方法所做的就是取用戶名和密碼登錄到Windows身份驗證的URL中,如果信譽正確,則返回true,如果它們不正確,則返回false。致命錯誤:意外地發現零,同時解開URLSession的可選值

這裏是方法:

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 

我相信我的問題是在這裏:

/** 
    Requests credentials from the delegate in response to a session-level authentication request from the remote server. 
    */ 

    func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { 

     if challenge.previousFailureCount > 0 
     { 
      completionHandler(Foundation.URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil) 
     } 
     else 
     { 
      completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust:challenge.protectionSpace.serverTrust!)) 
     } 

    } 

    /** 
    Requests credentials from the delegate in response to an authentication request from the remote server. 
    */ 

    func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { 

     completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential,credential) 

    } 

它不喜歡這些方法。

+0

例如,如果它的工作,我會接受你的答案。 – user979331

+1

'url'可能是零。 'requestString'的價值是什麼? – dan

+0

url與requestString不是零,它不是零 – user979331

回答

-1

變化從

let url: URL! = URL(string: requestString) 

到URL聲明:

let url: URL = URL(string: requestString)! 

這本身就可能解決它;或者它會顯示你的requestString不好。

+0

這沒有奏效,它並沒有解決我的問題 – user979331

0

這個答案適用於那些有這個問題但方式不同的人。
這是我面臨和修復: 我有一個搜索字段在tableview中查看一些結果。
它通過數字或刪除單詞崩潰並儘可能快地進行數字化。 我把一個例外斷點,但沒有顯示它崩潰的地方。因此,一個在胎面回來,並開始在此:

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 
} 

但是,到那裏digiting時,從這裏開始:

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 
} 

所以,當它刪除所有元素,它崩潰!
問題是DispatchQueue.main.asyncAfter(deadline: .now())
它有一個.now() + 0.2達拉然後,它沒有時間重新加載元素,導致崩潰!
現在它是實時擦除和填充,永遠不會再崩潰,因爲它填充單元格時永遠不會返回零。

希望可以幫助別人解決問題並找到錯誤!

相關問題