2016-10-03 3 views
2

Ich habe diese Methode, die in Swift 2.2 funktionierte, aber seit ich meinen Code in Swift 3 konvertiert hat funktioniert es nicht mehr, was diese Methode tut, ist ein Benutzername und Passwort Login in eine URL mit Windows-Authentifizierung, wenn die Kredits richtig sind, gibt es wahr, wenn sie nicht korrekt sind, wird es false zurückgeben. Hierfataler Fehler: unerwartet gefunden Null beim Entpacken ein Optionaler Wert mit URLSession

ist die Methode:

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() 

    } 

und ich bekomme diese Fehlermeldung:

fatal error: unexpectedly found nil while unwrapping an Optional value 

dies geschieht hier:

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) 
       } 

      }) 

     }) 

Was mache ich falsch?

Dies scheint in meinem Debug-Navigator vor dem fatalen Fehler:

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 

Ich glaube, mein Problem hier ist:

/** 
    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) 

    } 

es nicht, diese Methoden nicht mag.

+0

Beispiel bitte und wenn es funktioniert, werde ich Ihre Antwort akzeptieren. – user979331

+1

'URL' ist wahrscheinlich Null. Was ist der Wert von 'requestString'? – dan

+0

URL ist nicht gleich Null mit requestString, es ist nicht – user979331

Antwort

-1

Ändern Sie die URL Erklärung von

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

zu:

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

Das allein könnte es beheben; oder es wird zeigen, dass requestString schlecht ist.

+0

Das hat nicht funktioniert, es hat mein Problem überhaupt nicht behoben – user979331

0

Diese Antwort ist für diejenigen, die dieses Problem haben, aber auf andere Weise.
Hier ist, was ich konfrontiert und beheben: Ich habe ein Suchfeld, um einige Ergebnisse in der Tabellenansicht zu sehen.
Und es crash by digit oder lösche Wörter und digiting schnell wie möglich. Ich habe eine Ausnahme Break Point, aber nicht zeigen, wo es abstürzt. So erhielt ein in Stufe zurück und beginnen dazu:

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 
} 

Aber um dorthin zu gelangen, wenn digiting, es beginnt hier:

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 
} 

Also, wenn es alle Elemente entfernt, es zum Absturz!
Das Problem ist die DispatchQueue.main.asyncAfter(deadline: .now()).
Es hatte einen dalay von .now() + 0.2 und dann, es war nicht Zeit, Elemente erneut zu laden, was den Absturz verursacht!
Nun wird es in Echtzeit gelöscht und bevölkert und stürzt nie wieder ab, weil es niemals Null zurückgibt, wenn Zellen bevölkert werden.

Hoffe, jemand zu debugging zu helfen und den Fehler auch zu finden!

Verwandte Themen