如何在 Alamofire 获取请求中调用包含变量或常量的结构到字典中

Posted

技术标签:

【中文标题】如何在 Alamofire 获取请求中调用包含变量或常量的结构到字典中【英文标题】:How to call a Struct of variable or constant to include to Dictionary in Alamofire Get Request 【发布时间】:2018-08-24 03:27:54 【问题描述】:

我是使用 Swift 的新手,我使用 Alamofire 创建了一个 APIService,我尝试检查是否可以从 API 检索数据,结果很好。我现在的问题是,数据如何反映到我的 Event Struct 中的变量,所以我可以根据读取的数据执行一些验证。我试图通过断点检查,但变量无法读取数据或“”值。请帮我。谢谢

事件结构

struct Event: Codable 

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

    if let formattedStartDateTime = getDateFromString(dateString: startDateTime, formatString: "yyyy-MM-dd'T'HH:mm:ss.SSS") 
        self.startDateTime = formattedStartDateTime
    else 
        self.startDateTime = Date()
    

    if let deleteFlag = JSON["delete_flag"] as? Bool 
        self.deleteFlag = deleteFlag
    else 
        self.deleteFlag = nil
    

    if let deletedDateTime = JSON["deleted_datetime"] as? String 
        self.deleteDateTime = deletedDateTime
    else 
        self.deleteDateTime = nil
    

    if let dateCreated = JSON["date_created"] as? String 
        self.dateCreated = dateCreated
    else 
        self.dateCreated = nil
    

    if let hasRaffle = JSON["hasRaffle"] as? Bool 
        self.hasRaffle = hasRaffle
    else 
        self.hasRaffle = nil
    

    if let registrationReq = JSON["registration_req"] as? Bool 
        self.registrationReq = registrationReq
    else 
        self.registrationReq = nil
    

    if let closedFlag = JSON["closed_flag"] as? Bool 
        self.closedFlag = closedFlag
    else 
        self.closedFlag = nil
    

    if let closedDateTime = JSON["closed_datetime"] as? String 
        self.closedDateTime = closedDateTime
    else 
        self.closedDateTime = nil
    

    if let reopenFlag = JSON["reopen_flag"] as? Bool 
        self.reopenFlag = reopenFlag
    else 
        self.reopenFlag = nil
    

    if let reopenDateTime = JSON["reopen_datetime"] as? String 
        self.reopenDateTime = reopenDateTime
    else 
        self.reopenDateTime = nil
    


API服务

 class APIService
 
    let eventAPIKey: String
    let eventBaseURL: URL?

    //static let kEventID = "id"
   init(APIKey: String)
  
   self.eventAPIKey = APIKey
   eventBaseURL = URL(string: BASE_URL)
   

   func validatePasscode(passcode: String, completion: @escaping     (Event?) -> Void)
 
   let passcodeURL = URL (string: "\(PASSCODE_CHECKER_URL)/\(passcode)")


    Alamofire.request(passcodeURL!, method: .get).responseJSON  (response) in

      switch response.result
        case .success:

                if let passcodeJSON = response.result.value
                        print(passcodeJSON)
                    completion(Event(JSON: json as [String : Any]))
                    

      case .failure(let error):
           print("\(error)")
        

     

     


 

【问题讨论】:

如果你不打算使用任何内置的 Swift 4 编码/解码,你的结构不需要符合 Codable。 @rmaddy 谢谢我尝试了你的建议,但不幸的是 Thread 1: signal SIGABRT 出现在 completion(Event(JSON: json as! [String : AnyObject] )) 它显示 Could not cast value of type '__NSSingleObjectArrayI' (0x110df0608) to 'NSDictionary' (0x110df1288). 我该如何解决?谢谢 【参考方案1】:

您需要尝试使用收到的数据passcodeJSON 初始化Event 结构。如您所见,您的 Event 初始化程序是 init?(JSON: [String: AnyObject])

if let passcodeJSON = response.result.value
   // print(passcodeJSON)
   completion(Event(JSON: passcodeJSON))

以及调用 API 服务的位置:

apiServiceClient.validatePasscode(passcode: "testing")  eventDetails in 
   // do something with eventDetails here

【讨论】:

嗨!谢谢你的建议,我试着按照你的建议去做。 Thread 1: signal SIGABRT ,在我构建应用程序时出现在 completion(Event(JSON: json as! [String : AnyObject])) 行中。我该如何解决?谢谢 你能发布输出或其中的一部分吗?它一定是崩溃了,因为你要转换的数据类型不匹配 [String: AnyObject]

以上是关于如何在 Alamofire 获取请求中调用包含变量或常量的结构到字典中的主要内容,如果未能解决你的问题,请参考以下文章

如何在 alamofire 发布请求中发送 JSON 变量作为参数

如何使用 Alamofire 请求在我的 tableView 中显示我的数据

Moya/Alamofire 请求变量问题

为啥我无法从 Alamofire 获取请求结果

在类函数中调用 Alamofire 时出错

从后台获取调用时,Alamofire 不工作