0

I am creating an Event Manager App, It requires to input valid Event Code to check the Event Details. I am working on the Sign in page where in the user will input the event code. When the page is error free, I tried to clean, build and run the app, insert breakpoints to check the executions of my codes. But seems that I am encountering an issue, where in, whether I input valid code or not, It just loaded and after it loads, It goes back to a clear textfield, no error alerts or not event dispatch the Dashboard Page. I really can't figure out what's wrong with my codes. I am new in swift. I really need hep to fix it. Below are my codes for your reference and image of eventDetails from breakpoint. Thankyou

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 Function

   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
    }
  }
 }
pchocoios
  • 55
  • 11
  • Ok, one question. In validateEventPasscode method why do you check *guard let eventDetails = self.event*? – tereks Aug 20 '18 at 04:00
  • @tereks to check whether the passcode entered is valid or not and if its valid it should access the event details. – pchocoios Aug 20 '18 at 04:19
  • 1
    Ok, second question - are you aware that comma is == AND operator, so when you write *guard let eventDetails = self.event, error == nil* that means if event not nil AND error not nil then do following ... And you have another moment: *if let networkError = error { if networkError != error {* - what is this supposed to mean? First you create network error object and then comparing it to the same optional error object – tereks Aug 20 '18 at 04:28
  • 1
    Unrelated but a `JSONDictionary` in Swift 3+ is always `[String:Any]`, not `[String:AnyObject]`. And the function `makeHTTPPostRequest` makes no sense because it returns always `nil` and no data. And don't use `NS(Mutable)...` types at all in Swift if there is a native counterpart. – vadian Aug 20 '18 at 04:31
  • @tereks I'm not aware of that.if you don't mind, can I ask some help me by providing examples? so I understand very well. Thank you. – pchocoios Aug 20 '18 at 05:19
  • @vadian I used this codes https://gist.github.com/higepon/71f18472f6d4cba77870 as my reference to create my APIService.swift. – pchocoios Aug 20 '18 at 05:21
  • 1
    The code on GitHub is apparently written in Swift 2. If you are using Swift 3+ you should use `Any` as unspecified type. – vadian Aug 20 '18 at 05:59

0 Answers0