使用Alamofire + SwiftyJSON定义全局变量

时间:2016-12-27 18:37:12

标签: swift3 global-variables alamofire swifty-json

我正在使用Alamofire进行请求,我正在使用swiftyjson进行json解析。

我需要为其他视图控制器定义全局变量。

我有这段代码:

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
    }

}

我正在检查调试窗口,print(Settings.registration_url);看起来是空白的

为什么?

感谢。抱歉我的英语很差。

1 个答案:

答案 0 :(得分:0)

您的Settings结构不是全局的。您需要在类外定义它才能成为全局:

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
    }

}