使用添加了WebAPI参数的NSDictionary

时间:2017-11-12 16:38:15

标签: ios json swift

我在前言中说我对swift有点新意,并且只参加了一些介绍性课程,这些课程让我构建/修改我当前的应用程序。我的应用程序上的登录功能遇到了一些问题。我最近做了一些小改动(在API和前端应用程序中添加了几个字段以匹配,一个是类别)我已经开始看到一个错误,指出由于尝试插入一个未捕获的异常应用程序崩溃前的非属性列表对象。我一直试图改变结构(使用链ifs和guard)和Type(到NSMutableDictionary)以及设置一些逻辑来捕获看起来没有运气的传递的Null值。

这是来自控制台的JSON plus错误:

 Attempt to set a non-property-list object {
    imagePath = "<null>";
    email = "xxxx@xxxx.com";
    firstname = xxxx;
    id = 1;
    lastname = xxxxx;
    category = 1;
    message = "Logged in successfully";
    status = 200;
    username = xxxxxx;
 } as an NSUserDefaults/CFPreferences value for key parseJSON
 [7286:636470] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to insert non-property list object {
     ava = "<null>";
     email = "xxxxxxx@xxxxx.com";
     firstname = xxxx;
     id = 1;
     lastname = xxxxx;
     category = 1;
     message = "Logged in successfully";
     status = 200;
     username = xxxxxx;
 } for key parseJSON'

这是我对该对象的设置。

 //stores all information about current member
 var member : NSDictionary?


 @UIApplicationMain
 class AppDelegate: UIResponder, UIApplicationDelegate {

 var window: UIWindow?

 // image to be animated
 let backgroundImg = UIImageView()

 // boolean to check is erroView is currently showing or not
 var infoViewIsShowing = false


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


    // load content in member var
    member = UserDefaults.standard.value(forKey: "parseJSON") as? NSDictionary

    // if member has been logged in/registered, keep them logged in
    if member != nil {

        let id = member!["id"] as? String
        if id != nil {
            login()
        }

    }


    return true
 }

这是我用来获取/使用JSON的示例方法:

    // if text is entered

        // remove keyboard
        self.view.endEditing(true)

        // shortcuts
        let username = usernameTxt.text!.lowercased()
        let password = passwordTxt.text!

        // send request to API
        // set url
        let url = URL(string: "http://xxxx.xxx/xxxx/login.php")!

        // request url
        var request = URLRequest(url: url)

        // POST to the API
        request.httpMethod = "POST"

        // append body to url
        let body = "username=\(username)&password=\(password)"

        // append body to request
        request.httpBody = body.data(using: .utf8)

        // launch session
        URLSession.shared.dataTask(with: request) { data, response, error in

            // if there's no error
            if error == nil {

                do {
                    let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

                    guard let parseJSON = json else {
                        print("Error while parsing")
                        return
                    }

                    // remove keyboard


                    let id = parseJSON["id"] as? String

                    // successfully logged in
                    if id != nil {

                        // save member information from host
                        UserDefaults.standard.set(parseJSON, forKey: "parseJSON")
                        member = UserDefaults.standard.value(forKey: "parseJSON") as? NSDictionary

                        // go to home page
                        DispatchQueue.main.async(execute: { 
                            appDelegate.login()
                        })

                    // error
                    } else {

                        // get queue to send issue info to member
                        DispatchQueue.main.async(execute: {
                            let message = parseJSON["message"] as! String
                            appDelegate.infoView(message: message, color: colorSmoothRed)
                        })
                        return

                    }

                } catch {

                    // get queue to send issue info to member
                    DispatchQueue.main.async(execute: {
                        let message = "\(error)"
                        appDelegate.infoView(message: message, color: colorSmoothRed)
                    })
                    return

                }

            } else {

                // queue to send issue info to member
                DispatchQueue.main.async(execute: {
                    let message = error!.localizedDescription
                    appDelegate.infoView(message: message, color: colorSmoothRed)
                })
                return

            }

返回null值的字段是DB中的VARCHAR字段。除ID和类别(均为INT)之外的所有其他字段也是VARCHAR。如果还有其他需要的信息,请告诉我。

提前谢谢!

1 个答案:

答案 0 :(得分:0)

我发现我使用的方法仅适用于较旧版本的swift。我已经更新了代码来解析json使用:

 member = parseJSON

现在看起来按预期工作了。