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

时间:2018-03-30 03:01:49

标签: ios swift api alamofire swift4

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

1 个答案:

答案 0 :(得分:0)

使用我在下面提供的函数将您的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
}