【问题标题】:How to grab data from an API using Swift 4 and Alamofire如何使用 Swift 4 和 Alamofire 从 API 中获取数据
【发布时间】:2018-09-09 02:32:16
【问题描述】:

我正在尝试从没有文档的 API 获取数据。

我的代码是

let URL_MAIN = "http://evarsity.srmuniv.ac.in/srmswi/usermanager/youLogin.jsp"
let URL_ATTENDANCE = "http://evarsity.srmuniv.ac.in/srmswi/resource/StudentDetailsResources.jsp?resourceid=7"
let URL_TIMETABLE = "http://evarsity.srmuniv.ac.in/srmswi/resource/StudentDetailsResources.jsp?resourceid=5"

func getData(url: String) {

    Alamofire.request(url, method: .get)
        .responseData { response in
            if response.result.isSuccess {

                print("Sucess! Got the data")

                guard let data = response.result.value else { return }

                print(data)



            } else {
                print("Error: \(String(describing: response.result.error))")

            }
}

我收到的响应为 51406 字节。 我需要以 JSON 或其他格式获取实际数据。这是python的api链接

https://github.com/arjunmahishi/srm-erp-api/blob/master/erp.py

【问题讨论】:

  • 网址是什么?它返回什么值?你有这些信息吗?
  • 那里有三个网址。哪个有你需要的数据?似乎只有第一个指向任何东西,甚至那个有一个用户名、密码和验证码类型字段。基本上,我很确定那些不是 API 端点。此外,在 swift 中,常量并非像 Java 中那样全部大写且带有下划线,而是使用 let 而不是 var 定义的普通变量名。
  • 这三个都不是 API,都是页面,它为您提供页面代码(HTML/Java 脚本)。

标签: ios swift api alamofire swift4


【解决方案1】:

使用我在下面提供的函数将您的 responseData 转换为字典,然后相应地解析数据。在这里,我得到一个字典形式的 JSON 响应。

let strResponse = "\(responseString.value!)"
let arr = strResponse.components(separatedBy: "\n")
let dict =  convertStringToDictionary(str:(arr.last  ?? "")!) 
self.Message = dict?["message"] as! String
let responseStatus = dict?["status"] as! NSString


public func convertStringToDictionary(str:String) -> [String: Any]? {
    if let data = str.data(using: .utf8) {
        do {
            return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
        } catch {
            print(error.localizedDescription)
        }
    }
    return nil
}

【讨论】:

    猜你喜欢
    • 2019-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-19
    • 1970-01-01
    • 2019-08-19
    • 2021-04-25
    • 2023-04-02
    相关资源
    最近更新 更多