无法弄清楚为什么Error总是变成'nil'

时间:2018-08-20 01:50:11

标签: ios swift api nsurlsession json-serialization

我正在创建一个事件管理器应用,它需要输入有效的事件代码以检查事件详细信息。我正在“登录”页面上工作,在该页面中用户将输入事件代码。当页面没有错误时,我尝试清理,构建和运行应用程序,插入断点以检查代码的执行情况。但是似乎我遇到了一个问题,无论我是否输入有效的代码,它都已加载,加载后才返回,它返回一个清晰的文本字段,没有错误警报或没有事件调度仪表板页面。我真的不知道我的代码出了什么问题。我是新手。我真的很需要修复它。以下是我的代码供您参考,以及来自断点的 eventDetails 图像。谢谢

eventDetails with nil values

APIService.swift

  typealias JSONDictionary = Dictionary<String, AnyObject>

  class APIService: NSObject, URLSessionDataDelegate {

  enum Path {
      case SubmitEventCode
   }

  typealias APICallback = ((AnyObject?, NSError?) -> ())
  let responseData = NSMutableData()
  var statusCode: Int = -1
  var callback: APICallback! = nil
  var path: Path! = nil


  func validatePasscode(eventcode: String!, callback: @escaping APICallback) 
  {
  let url = PASSCODE_CHECKER_URL //https://hopprLab.com/API/events/PasscodeChecker
  makeHTTPPostRequest(path: Path.SubmitEventCode, callback: callback, url: url)
  }

    func connection(_ connection: URLSession, didReceive response: URLResponse){
    let httpResponse = response as! HTTPURLResponse
    statusCode = httpResponse.statusCode
    switch (httpResponse.statusCode) {
    case 201, 200, 401:
    self.responseData.length = 0
    default:
    print("ignore")
      }
    }

   func connection(_ connection: URLSession, didReceive data: Data) {
    self.responseData.append(data)
   }

   func connectionDidFinishLoading(_ connection: URLSession) {
    let error: NSError? = nil
    let json = try? JSONSerialization.jsonObject( with: responseData as Data, options:[]) as AnyObject
     if ((data) != nil) {
        callback(nil, error)
         return
      }

   switch(statusCode, self.path!) {
   case(200, Path.SubmitEventCode):
      callback(self.handleValidatePasscode(json: json!) as     AnyObject,nil)
   default:
    //UnknownError
     callback(nil, nil)
      }
    }

   func handleAuthError(json: AnyObject) -> NSError {
   if let eventObj = json as? JSONDictionary {
   //
   if let messageObj: AnyObject = eventObj["error"] {
    if let message = messageObj as? String {
        return NSError(domain: "validatePasscode", code: 200, userInfo: ["error": message])
      }
    }
  }
   return NSError(domain: "validatePasscode", code: 200, userInfo:      ["error": "unknown auth error"])
  }


 func handleValidatePasscode(json: AnyObject) -> Event? {
     if let eventObj = json as? JSONDictionary{
         if let eventid: AnyObject = eventObj["event_id"]{
            if let eventJson = eventid as? JSONDictionary {
                if let eventpass = Event.init(JSON: eventJson){
                return eventpass
              }
          }
      }
  }
   return nil
}

//private

 func makeHTTPPostRequest(path: Path, callback: @escaping APICallback, url: String) {
    self.path = path
    self.callback = callback

  var request = URLRequest(url: NSURL(string: url)! as URL)

  request.httpMethod = "POST"
  request.addValue("application/json", forHTTPHeaderField: "content-type")
  request.addValue("application/json", forHTTPHeaderField: "Accept")

  let configuration = URLSessionConfiguration.default
  let session = URLSession(configuration: configuration)

  let dataTask = session.dataTask(with: request, completionHandler: {
    (data: Data?, response: URLResponse?, error: Error?) -> Void in
    if data != nil {
        DispatchQueue.main.async {
            callback(nil,nil)
        }
    }

})

dataTask.resume()
 }
}

Event.swift

struct Event {

let id: String
let name: String
let location: String
let startDateTime: Date
let endDateTime: String
let deleteFlag: Bool?
let deleteDateTime: String?
let dateCreated: String?
let hasRaffle: Bool?
let registrationReq: Bool?
let participantCount: Int
let closedFlag: Bool?
let closedDateTime: String?
let reopenFlag: Bool?
let reopenDateTime: String?


init?(JSON: [String: AnyObject]) {

guard let eventID = JSON["event_id"] as? String,
    let eventName = JSON["event_name"] as? String,
    let eventLocation = JSON["event_location"] as? String,
    let startDateTime = JSON["start_datetime"] as? String,
    let endDateTime = JSON["end_datetime"] as? String,
    let participantCount = JSON["participant_count"] as? Int else      {

        return nil
}

self.id = eventID
self.name = eventName
self.location = eventLocation
self.endDateTime = endDateTime
self.participantCount = participantCount

validatePasscode函数

   func validateEventPasscode() {
   //Show Loading
   self.view.squareLoading.start(0.0)

   let api = APIService()
   api.validatePasscode(eventcode: eventCode) { (data, error) in

    guard let eventDetails = self.event, error == nil else {

    if let networkError = error {
       if networkError != error {
         _ = SCLAlertView(appearance: appearance).showError("Ooops", subtitle: "Please enter valid event code")
       else {
        _ = SCLAlertView(appearance: appearance).showError("Network Error", subtitle: "Network Error")

        }
          }

    guard eventDetails.deleteFlag else {
        _ = SCLAlertView(appearance: appearance).showError("Ooops!", subTitle: "Please enter a valid event passcode")
        self.view.squareLoading.stop(0.0)
        return
    }

    if eventDetails.closedFlag == true && eventDetails.reopenFlag == false {
        _ = SCLAlertView(appearance: appearance).showError("Closed Event", subTitle: "Please check the status of your event and try again")

        self.view.squareLoading.stop(0.0)
        return
    }
  }
 }

0 个答案:

没有答案