2016-10-03 6 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と同じではありません.nilではありません。 – user979331

答えて

-1

変更

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

からのURL宣言:一人でそれを修正する可能性がある

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

requestStringが悪いことが表示されます。

+0

これは機能しませんでしたが、問題はまったく修正されませんでした – user979331

0

この回答は、この問題を抱えていますが、その方法が異なります。
これは私が直面している問題です: 私はテーブルビューでいくつかの結果を見て検索フィールドがあります。
それは、数字で潰れたり、単語を消去したり、できるだけ早く掘ったりします。 私はException Break Pointを置いていますが、クラッシュする箇所は表示しません。だから、トレッドに戻ったし、それがこの上で開始:

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のダレイを持っていましたが、再び要素をリロードしてクラッシュを引き起こす時間がありませんでした!
これで、リアルタイムでの消去とポピュレートが行われ、再びセルにクラッシュすることはありません。

誰かを掘り下げてエラーを見つけるのを助けることを望みます!

関連する問題