Define global variable with Alamofire + SwiftyJSON

324 Views Asked by At

I'm using Alamofire for requests and i'm using swiftyjson for json parsing.

I need define global variables for other view controllers.

I have this code:

import UIKit
import Alamofire
import SwiftyJSON

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    struct Settings {
        static var registration_url = String();
        static var login_url = String();
    }

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        Alamofire.request("http://localhost/settings.php").responseJSON { response in

            if response.result.isSuccess {

                let json = JSON(data: response.data!);

                Settings.registration_url = json["registration_url"].stringValue;
                Settings.login_url = json["login_url"].stringValue;

            } else {

                Settings.registration_url = "http://localhost/register.php";
                Settings.login_url = "http://localhost/login.php";

            }

        }

        print(Settings.registration_url);
        print(Settings.login_url)

        return true
    }

}

I'm checking debug window, and print(Settings.registration_url); is looks blank

Why?

Thanks. Sorry for my poor english.

1

There are 1 best solutions below

0
On

Your Settings structure is not global. You need to define it outside the class for it to be global:

struct Settings {
    static var registration_url = String();
    static var login_url = String();
}

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        Alamofire.request("http://localhost/settings.php").responseJSON { response in

            if response.result.isSuccess {

                let json = JSON(data: response.data!);

                Settings.registration_url = json["registration_url"].stringValue;
                Settings.login_url = json["login_url"].stringValue;

            } else {

                Settings.registration_url = "http://localhost/register.php";
                Settings.login_url = "http://localhost/login.php";

            }

        }

        print(Settings.registration_url);
        print(Settings.login_url)

        return true
    }

}