I have a static function called connection(...) that uses URLSESSION to make a REQUEST. This is called in many areas of my application. In this example, it is called from an @IBAction.
The issue is that I cannot return the variable resultData within the DataTask completion handler. It is important to know that I am new to Swift and it has been an adjustment from C# and UWP :-)
Triggering Event (NSViewController)
class PropertiesPageViewController: NSViewController {
@IBAction func GetCoursesButtonAction(_ sender: Any)
{
let d:Data = Canvas.connection(Authorization: Canvas.auth(URL: CanvasURLS.URL.Courses , params: "enrollment_state=active"), Method: Canvas.method.Get);
let json = try? JSONSerialization.jsonObject(with: d, options: []);
}
}
Canvas Class
class Canvas
{
enum method:String {
case Get = "GET"
case Post = "POST"
case Delete = "DELETE"
}
static func connection(Authorization:String, Method:method) -> Data
{
// CREATE URL
let url = URL(string: Authorization)!;
// CREATE REQUEST
var request = URLRequest(url: url);
request.httpMethod = Method.rawValue;
// START SESSION
let session = URLSession.shared;
session.dataTask(with: url, completionHandler: { (data, response , error) in
guard let resultData = data else { return; }
// NEED TO RETURN variable 'resultData' &
// CANNOT RETURN b/c 'dataTask' throws -> void
}).resume();
// return resultData;
// obviously that variable is not defined in the scope so there is an error
}
func auth() -> String {...}
// FUNCTION FORMATS THE URL FOR THE API CALL
// EXAMPLE RETURN: https://domain.instructure.com/api/v1/courses?access_token=xx¶ms[]
}