简体   繁体   中英

API request isn't giving a response

I am trying to use ( https://collegescorecard.ed.gov/data/documentation/ ) to populate a table in my ios app, but there isn't any data displaying. I have tried my api keys and the url a bunch of times so I don't think its that. Structure of the json file

Dev-category school

Name String The institution's name (INSTNM), as reported in IPEDS.

import UIKit
import Alamofire

class ViewController: UIViewController {
    let URLStr = "https://api.data.gov/ed/collegescorecard/v1/schools?fields=school.name"

    var resultArray = [Users]()
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var searchBar: UISearchBar!
     var searchCollege = [String]()

override func viewDidLoad() {
         super.viewDidLoad()
         tableView.dataSource = self
         tableView.delegate = self
         callAPI()


            }
    override func didReceiveMemoryWarning() {
           super.didReceiveMemoryWarning()
       }

func callAPI() {
        let key = "key redacted"
        //let url = URL(string:"\(URLStr)?api_key=\(key)")
        let url = URL(string:"\(URLStr)&api_key=\(key)")
        print(url)
        Alamofire.request(url!, method: .get, parameters: nil, headers:[:]).responseJSON {(response) in
            if let responseObj = response.value as? [[String: Any]]{
                self.resultArray = self.parseJSON(userData: responseObj)
                print("response here", response)
                self.tableView.reloadData()
                }
        }

}
func parseJSON(userData: [[String:Any]])-> [Users] {
    var userArr = [Users]()
    for obj in userData {
        do { let data = try JSONSerialization.data(withJSONObject: obj, options: .prettyPrinted)
            let decodedData = try JSONDecoder().decode(Users.self, from: data)
            userArr.append(decodedData)
            }

    catch {

        }
    }
        return userArr
    }
}

userModal.swift

mport Foundation
struct Users: Codable {
    let userSchool_name: String?
}
enum CodingKeys: String, CodingKey {
    case userSchool_name = "school.name"
}

I have tried to print out the response and the different objects but nothing prints out. I have a function below that displays it in the app, but I don't think that is the problem.

json output

SUCCESS: {
    metadata =     {
        page = 0;
        "per_page" = 20;
        total = 7112;
    };
    results =     (
                {
            "school.name" = "West Michigan College of Barbering and Beauty";
        },
                {
            "school.name" = "Georgia College & State University";
        },
                {
            "school.name" = "Georgia Southern University";
        },
                {
            "school.name" = "Clayton  State University";
        },
                {
            "school.name" = "Andrew College";
        },
                {
            "school.name" = "Columbus Technical College";
        },
                {
            "school.name" = "Georgia Northwestern Technical College";
        },
                {
            "school.name" = "Atlanta Metropolitan State College";
        },
                {
            "school.name" = "Clark Atlanta University";
        },
                {
            "school.name" = "Augustana College";
        },
                {
            "school.name" = "Miami Ad School at Portfolio Center";
        },
                {
            "school.name" = "Tricoci University of Beauty Culture-Urbana";
        },
                {
            "school.name" = "University of Hawaii at Manoa";
        },
                {
            "school.name" = "Aveda Institute-Twin Falls";
        },
                {
            "school.name" = "Cameo Beauty Academy";
        },
                {
            "school.name" = "Truett McConnell University";
        },
                {
            "school.name" = "Cannella School of Hair Design-Chicago";
        },
                {
            "school.name" = "Valdosta State University";
        },
                {
            "school.name" = "American Academy of Art";
        },
                {
            "school.name" = "City Colleges of Chicago-Kennedy-King College";
        }
    );
}

First of all delete parseJSON , it makes no sense to convert the JSON to an array, then back to JSON and then to a struct with JSONDecoder

 
 
  
  func parseJSON(userData: [[String:Any]])-> [Users] { var userArr = [Users]() for obj in userData { do { let data = try JSONSerialization.data(withJSONObject: obj, options: .prettyPrinted) let decodedData = try JSONDecoder().decode(Users.self, from: data) userArr.append(decodedData) } catch { } } return userArr } }
 
 

Then you have to add a struct for the root object

struct Root: Codable {
    let results : [Users]
}

struct Users: Codable {
    let userSchool_name: String?

     private enum CodingKeys: String, CodingKey {
        case userSchool_name = "school.name"
     }
}

And replace the Alamofire part with

   Alamofire.request(url!).responseData { response in
        switch response.result {
            case .success(let data):
                do {
                    self.resultArray = try JSONDecoder().decode(Root.self, from: data).results
                    self.tableView.reloadData()
                } catch {
                    print(error)
            }
            case .failure(let error):
                print(error)
        }
    }

It receives Data rather than a decoded array and handles all errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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