繁体   English   中英

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

[英]How to grab data from an API using Swift 4 and Alamofire

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

使用下面提供的功能将您的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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM