Adding callback to a class function in swift
In my project, I created a public class to handle my network communication for data requests (JSON, images, etc.). The function inside the class uses Alamofire to establish a network connection and load a JSON file.
Class and function below:
import Foundation
import Alamofire
public class DataConnectionManager {
public class func getJSON(AppModule:String, callback:(Int) -> Void) -> Void {
switch(AppModule) {
case "Newsfeed":
Alamofire.request(.GET, "http://some-site.com/api/", encoding: .JSON).responseJSON { (_, _, JSONData, _) in
if JSONData != nil {
jsonHolder.jsonData = JSONData!
print("start")
callback(1)
}
else {
callback(0)
}
}
break
default:
break
}
}
}
I am calling a function in my project like below:
DataConnectionManager.getJSON("Newsfeed", callback: { (intCheck : Int) -> Void in
if intCheck == 1 {
println("Success")
}
else {
println("Failure")
}
})
The app will launch without any error, however my health checks are not printing. In fact, when I do it like this, Alamofire.request is not grabbing the JSON feed.
Am I heading in the right direction with this?
I got this to work, but I'm not sure exactly how. I changed a couple of things based on user suggestions (adding error checking, etc.) and it magically started working. Here's my updated code so people can see how to add a callback to their functions.
My "ConnectionManager":
import Foundation
import Alamofire
public class DataConnectionManager {
public class func getJSON(AppModule:String, callback:(Int) -> Void) -> Void {
switch(AppModule) {
case "Newsfeed":
Alamofire.request(.GET, "http://some-site.com/api/", encoding: .JSON).responseJSON { (_, _, alamoResponse, error) in
if (error != nil){
println("You've got a response error!")
callback(0)
}
else {
if alamoResponse != nil {
jsonHolder.jsonData = alamoResponse!
callback(1)
}
else {
println("You've got some random error")
callback(0)
}
}
}
break
default:
break
}
}
}
My function call:
DataConnectionManager.getJSON("Newsfeed", callback: { (intCheck : Int) -> Void in
if intCheck == 1 {
self.createTable()
}
else {
println("Failure")
}
})
I am using swift 2.0 + SwiftyJSON and this is my code to implement this:
class func getJSON(AppModule:String, urlToRequest: String, resultJSON:(JSON) -> Void) -> Void {
var returnResult: JSON = JSON.nullJSON
switch(AppModule) {
case "all":
request(.GET, urlToRequest)
.responseJSON { (_, _, result) in
if (result.isFailure){
print("You've got a response error!")
resultJSON(nil)
}
else {
if (JSON(result.value!) != nil) {
returnResult = JSON(result.value!)
resultJSON(returnResult)
}
else {
print("You've got some random error")
}
}
}
break
default:
break
}
}
And call the function like this:
DataManager.getJSON("all",urlToRequest: "myurl.com", resultJSON: { (result: JSON) -> Void in
if (result == nil){
// error with result json == nil
return
}else{
//do something with json result
}
})
Hope this can be helpful.