从“字符串”转换?无关类型“ [String:String]”始终失败

时间:2019-03-07 20:09:12

标签: swift

在从数据库中获取的json响应中选择密钥后,我试图通过使用带有标识符的segue将LogInViewController切换到主屏幕。我没有收到任何错误,但是有一个警告

  

“从字符串中广播?”无关类型'[String:String]'总是失败”

我认为是问题所在。

点击登录按钮后的日志显示:

"Result: SUCCESS
{"status":true,"message":"Successful Login"}  
{"user":{"userID":3,"email":"becky1","Final-Score":1,"Game-Reminder":1,"Stat-Update":0,"Game-Start":0}}"

我的完整代码:

import UIKit
import Alamofire
import GoogleSignIn
import SwiftyJSON

class LogInViewController: UIViewController,GIDSignInUIDelegate, GIDSignInDelegate {
    @IBOutlet weak var lblTitle: UILabel!
    @IBOutlet weak var btnGoogleSignIn:UIButton!

    //you can get the ip using ifconfig command in terminal
    let URL_USER_LOGIN = "http://cgi.sice.indiana.edu/~team58/login.php"

    let defaultValues = UserDefaults.standard

    @IBOutlet weak var textFieldEmail: UITextField!
    @IBOutlet weak var textFieldPassword: UITextField!


    override func viewDidLoad() {
        super.viewDidLoad()
        ///Google Sign in////
        btnGoogleSignIn.addTarget(self, action: #selector(signinUserUsingGoogle(_:)), for: .touchUpInside)
        // Do any additional setup after loading the view, typically from a nib.

    }

    @objc func signinUserUsingGoogle(_ sender: UIButton) {
        if btnGoogleSignIn.title(for: .normal) == "Sign Out" {
            GIDSignIn.sharedInstance().signOut()
            lblTitle.text = ""
            btnGoogleSignIn.setTitle("Sign in Google", for: .normal)
        } else {

            GIDSignIn.sharedInstance().delegate = self
            GIDSignIn.sharedInstance().uiDelegate = self
            GIDSignIn.sharedInstance().signIn()



        }

    }

    func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
        if let error = error {
            print("We have error signing in user == \(error.localizedDescription)")
        } else {
            performSegue(withIdentifier: "popOutNoteExpanded", sender: self)
            if let gmailUser = user {
                lblTitle.text = "You are signed in using id \(gmailUser.profile.email)"
                btnGoogleSignIn.setTitle("Sign Out", for: .normal)

                /// end google sign in ///
            }
        }
    }


    @IBAction func LoginButton(_ sender: UIButton) {
        let parameters: Parameters=[
            "email":textFieldEmail.text!,
            "password":textFieldPassword.text!
        ]

        //making a post request
        Alamofire.request(URL_USER_LOGIN, method: .post, parameters: parameters).responseString
            {
                response in

//                print("Request: \(String(describing: response.request))")   // original url request
//                print("Response: \(String(describing: response.response))") // http url response
                print("Result: \(response.result)")
                print(response.result.value!)

//
//                //self.ResponseLabel.text = "Result: \(response.result)"

                if let result = response.result.value as? [String:String] {



                    //if there is no error

//                    if result["SUCCESS"] {

                    if result["message"] == "Succesful Login" {



                        //getting the user from response

                        //getting user values - not neccesary
                        if let userEmail = result["email"] {
                           self.defaultValues.set(userEmail, forKey: "email")
                        }
                        if let userPassword = result["password"] {
                          self.defaultValues.set(userPassword, forKey: "password")
                        }
                        self.performSegue(withIdentifier: "popOutNoteExpanded", sender: self)




//
                        } else  {
                        //error message in case of invalid credential
                      // original url request
//                        print("Response: \(String(describing: response.response))") // http url response

                        print("invalid credentials")

                    }



}
}
}



}

2 个答案:

答案 0 :(得分:1)

问题是response.result.value具有可选的String类型。但是您尝试在此处投射为[String: String]的字典

 if let result = response.result.value as? [String:String] {

此代码安全地对其进行检查,但强制转换显然失败。 要解决此问题,您必须将incode字符串解析为json对象,以便检索数据。

Swift 4使用Codable来完成这项工作。 Documentation或使用具有相同功能的Alamofire API:此方法responseJSON

答案 1 :(得分:0)

有很多方法可以将可选字符串转换为字典。

您可以使用本机JSONSerialization

guard let text = response.result.value as? String else { return } 
    if let data = text.data(using: String.Encoding.utf8) {
        do {
            let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:String]
            print(json) // safely use json
        } catch {
            print("Error")
        }
    }