I am currently trying to clean up my code on a project by writing a generic function that can be used multiple times. However i need my function to return an array. My error is
You can't return data directly from an asynchronous task. Use a closure
Create a Function using a closure like.
func JSONSerialisation(JsonUrl: String, Completion block: @escaping ((NSArray) -> ())){
let url = URL(string: JsonUrl)
let task = URLSession.shared.dataTask(with: url!) { (data, responce, error) in
if let e = error{
print(e.localizedDescription)
}
else{
if let content = data{
do {
if let Json = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSArray{
block(Json)
}
}
catch let error{
print(error.localizedDescription)
}
}
}
}
task.resume()
}
And Call :
JSONSerialisation(JsonUrl: "Your Url") { (json) in
print(json)
}
This is helpful