2016-10-03 2 views
2

스위프트 2.2에서 작동했던이 방법을 사용했지만 스위프트 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'은 아마도 nil 일 것입니다. 'requestString'의 값은 무엇입니까? – dan

+0

url이 requestString과 nil이 아니며 nil이 아닙니다. – 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 인 경우 요소를 다시로드 할 시간이 없어 충돌이 발생합니다!
이제 실시간으로 지우고 채우고 다시 충돌하지 않습니다. 셀을 채울 때 결코 되돌아 오지 않기 때문입니다.

오류를 찾아 내고 오류를 찾는 데 도움이되기를 바랍니다.

관련 문제