如何使用 Swift 4 和 Alamofire 从 API 获取数据

问题描述 投票:0回答:1

我正在尝试从没有文档的 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

ios swift alamofire swift4
1个回答
-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
}
© www.soinside.com 2019 - 2024. All rights reserved.