I have this function recovering the player score from a MySQL database. From other tutorials, I have found the URLSession approach useful when sending data out from the app, but would I be able to actually use the return of the function anywhere? Kept searching for something like a
task.resume()
task.end()
return (rank, name, score)
?
func downloadLocalScores(_ choice: Int) -> ([String], [String], [String]) {
var url: URL
let id: String = getUserID("id")
if choice == 0 {
url = NSURL(string: "myPHPscript.php")! as URL
} else {
url = NSURL(string: "myPHPscript2.php")! as URL
}
let request = NSMutableURLRequest(url: url)
request.httpMethod = "POST"
let postString = "id=\(id)"
request.httpBody = postString.data(using: String.Encoding.utf8)
var name: [String] = []
var score: [String] = []
var rank: [String] = []
if Reachability().isInternetAvailable() == true {
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if error == nil {
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
let variables = try! JSONSerialization.jsonObject(with: data! as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSArray
for i in 0..<variables.count {
let level = variables[i] as! [String:AnyObject]
name.append(level["name"] as! String)
score.append(level["score"] as! String)
rank.append(level["rank"] as! String)
}
} else {
print(error)
}
}
task.resume()
return (rank, name, score)
} else {
return (["NO CONNECTION"], ["0"])
}
}
I have another function to download scores, but being a request for top scores, doesn't need to take any input from app
func downloadScores(_ choice: Int) -> ([String], [String]) {
var url: URL
if choice == 0 {
url = NSURL(string: "myPHPscript.php")! as URL
} else {
url = NSURL(string: "myPHPscript2.php")! as URL
}
let data = NSData(contentsOf: url)
var variables: NSArray = []
if Reachability().isInternetAvailable() == true {
variables = try! JSONSerialization.jsonObject(with: data! as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSArray
var name: [String] = []
var score: [String] = []
for i in 0..<variables.count {
let level = variables[i] as! [String:AnyObject]
name.append(level["name"] as! String)
score.append(level["score"] as! String)
}
return (name, score)
} else {
return (["No connection"], [""])
}
}
I am still not perfectly familiar with other options of sending data out of my app, so could the last function be adapted to POST? Have tried something last night but got stuck at data = NSData asking for a type URL instead of the NSMutableURLRequest I had.
Should mention I created global variables and append inside first function, but the result is recovered after they are used and I can't find a way to delay or refresh once they have been filled. I don't mind app waiting for them, as they are used after the viewDidLoad().