I am trying to create a function that will build an array of soccer players from an api using swiftyJSON. Each player needs an array entry containing a bool value that is always true, as well as "id", "fullname" and "photo" from the JSON data (all as strings). The resulting array must be available throughout my project as it will be used to populate labels and UIImageViews.
How do I return such an array via a function. Below is as far as I could get:
// Celtic soccerama api
let baseURL = "https://api.soccerama.pro/v1.2/players/team/152?api_token=9b2LKV6TjmYEkzCjeB1efeWXeCRcNAGXkph1CjzmWYMKs4F3a1KrWh9paXIa"
struct global {
static var celticData : [(Bool, String, String, String)] = []
}
// JSON all Celtic players
func getData() -> [(Bool, String, String, String)]? {
var data : Array = [(Bool, String, String, String)]()
let url = NSURL(string: baseURL)
let request = NSURLRequest(URL: url!)
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
let task = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
if error == nil {
// Get the data returned from NSURLRequest
let swiftyJSON = JSON(data: data!)
// Loop through "data" array and pull out "id", "fullname" and "photo"
// Won't work:
//for i in 0 ... swiftyJSON["data"].count {
// Have to manually count
for i in 0 ... 10 {
// Add bool (true every time)
let t = true
data[i].0 = t
// Get data and append at each position in array
let id = swiftyJSON["data"][i]["id"].stringValue
let fullName = swiftyJSON["data"][i]["fullname"].stringValue
// Get image data for display and append to array
let imageArrayPosition = swiftyJSON["data"][i]["photo"].stringValue
let imageURL = NSURL(string: imageArrayPosition)
}
} else {
print("There was an error")
}
}
task.resume()
}