iOS swift 3.0 Json解析和警报问题

iOS swift 3.0 Json解析和警报问题,swift,Swift,我正在做登录表单。我是iOS开发的新手 成功登录后,我想在json解析完成后显示一个警报。我在do while块中解析了Ngoid。现在我想将值“Ngoid”传递给下一个视图控制器,以便可以使用它获取进一步的数据 主要问题:这是我编写的代码,如果只在主线程上编写警报,就会出现错误 因为我希望“Ngoid”值在那里进一步使用,所以我应该如何编写它,以及执行代码的正确方式是什么 以下是我编写的代码: @IBAction func loginbutton(_ sender: Any) { le

我正在做登录表单。我是iOS开发的新手

成功登录后,我想在json解析完成后显示一个警报。我在
do while
块中解析了
Ngoid
。现在我想将值“Ngoid”传递给下一个视图控制器,以便可以使用它获取进一步的数据

主要问题:这是我编写的代码,如果只在主线程上编写警报,就会出现错误

因为我希望“Ngoid”值在那里进一步使用,所以我应该如何编写它,以及执行代码的正确方式是什么

以下是我编写的代码:

@IBAction func loginbutton(_ sender: Any) {
    let myUrl = NSURL(string: "http://www.shreetechnosolution.com/funded/ngo_login.php")

    let request = NSMutableURLRequest(url:myUrl! as URL)

    request.httpMethod = "POST"// Compose a query string

    let postString = "uname=\(textfieldusername.text!)&password=\(textfieldpassword.text!)";

    request.httpBody = postString.data(using: String.Encoding.utf8)



    let task = URLSession.shared.dataTask(with: request as URLRequest){ data , response , error in

        if error != nil
        {
            //let alert = UIAlertView()
            let alert = UIAlertController(title: "Alert Box !", message: "Login Failed", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
            return
        }

        // You can print out response object
        print("*****response = \(String(describing: response))")

        let responseString = NSString(data: data! , encoding: String.Encoding.utf8.rawValue )

        if ((responseString?.contains("")) == nil) {
            print("incorrect - try again")

            let alert = UIAlertController(title: "Try Again", message: "Username or Password Incorrect", preferredStyle: .alert)
            let yesAction = UIAlertAction(title: "Nochmalversuchen", style: .default) { (action) -> Void in

            }


            // Add Actions
            alert.addAction(yesAction)


            // Present Alert Controller
            self.present(alert, animated: true, completion: nil)
        }

        else {
            print("correct good")


        }

        print("*****response data  = \(responseString!)")




        do {
            //create json object from data

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

                if let email = json["UserName"] as? String,
                    let password1 = json["passowrd"] as? String {

                    print ("Found User id:  called \(email)")
                }
                let msg = (json.value(forKey: "message") as! NSString!) as String
               let id = (json.value(forKey: "NgoId") as! NSString!) as String


//                    let alert : UIAlertView = UIAlertView(title: "Alert box!", message: "\(msg!).",delegate: nil, cancelButtonTitle: "OK")
//                    alert.show()

                self.alert = UIAlertController(title: "Alert Box!", message: "\(msg)", preferredStyle: .alert)
                print("the alert\(self.alert)")
                self.action = UIAlertAction(title: "OK", style: .default) { (action) -> Void in
                    let viewControllerYouWantToPresent = self.storyboard?.instantiateViewController(withIdentifier: "pass1") as! ViewControllerngodetails

                    viewControllerYouWantToPresent.temp1 = self.id

                    self.present(viewControllerYouWantToPresent, animated: true, completion: nil)

                }

                self.alert.addAction(self.action)

                self.present(self.alert, animated: true, completion: nil)



            }




        }catch let error {
            print(error)
        }



    }
    task.resume()

        }
专业提示:

所有与UI相关的任务都需要在主线程中完成。在这里,您将在后台线程中执行的闭包中显示警报,这就是问题所在。您需要调用主队列并在该块中显示警报

编辑:

只要把你的警报代码放在这里-

斯威夫特3-

异步获取主队列

DispatchQueue.main.async {
    //Code Here
}
DispatchQueue.main.sync {
    //Code Here
}
同步获取主队列

DispatchQueue.main.async {
    //Code Here
}
DispatchQueue.main.sync {
    //Code Here
}
专业提示:

所有与UI相关的任务都需要在主线程中完成。在这里,您将在后台线程中执行的闭包中显示警报,这就是问题所在。您需要调用主队列并在该块中显示警报

编辑:

只要把你的警报代码放在这里-

斯威夫特3-

异步获取主队列

DispatchQueue.main.async {
    //Code Here
}
DispatchQueue.main.sync {
    //Code Here
}
同步获取主队列

DispatchQueue.main.async {
    //Code Here
}
DispatchQueue.main.sync {
    //Code Here
}

每个UI更新都必须在主线程上:

@IBAction func loginbutton(_ sender: Any) {
    let myUrl = NSURL(string: "http://www.shreetechnosolution.com/funded/ngo_login.php")

    let request = NSMutableURLRequest(url:myUrl! as URL)

    request.httpMethod = "POST"// Compose a query string

    let postString = "uname=\(textfieldusername.text!)&password=\(textfieldpassword.text!)";

    request.httpBody = postString.data(using: String.Encoding.utf8)



    let task = URLSession.shared.dataTask(with: request as URLRequest){ data , response , error in

    if error != nil
    {
        DispatchQueue.main.async {
            let alert = UIAlertController(title: "Alert Box !", message: "Login Failed", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
            // Present Alert Controller
            self.present(alert, animated: true, completion: nil)
        }
        return
    }

        // You can print out response object
        print("*****response = \(String(describing: response))")

        let responseString = NSString(data: data! , encoding: String.Encoding.utf8.rawValue )

        if ((responseString?.contains("")) == nil) {
            print("incorrect - try again")
            DispatchQueue.main.async {
                let alert = UIAlertController(title: "Try Again", message: "Username or Password Incorrect", preferredStyle: .alert)
                let yesAction = UIAlertAction(title: "Nochmalversuchen", style: .default) { (action) -> Void in }

                // Add Actions
                alert.addAction(yesAction)

                // Present Alert Controller
                self.present(alert, animated: true, completion: nil)
            }
        }

        else {
            print("correct good")
        }

        print("*****response data  = \(responseString!)"

        do {
            //create json object from data

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

                if let email = json["UserName"] as? String,
                    let password1 = json["passowrd"] as? String {

                    print ("Found User id:  called \(email)")
                }
                let msg = (json.value(forKey: "message") as! NSString!) as String
               let id = (json.value(forKey: "NgoId") as! NSString!) as String

                DispatchQueue.main.async {
                    self.alert = UIAlertController(title: "Alert Box!", message: "\(msg)", preferredStyle: .alert)
                    print("the alert\(self.alert)")
                    self.action = UIAlertAction(title: "OK", style: .default) { (action) -> Void in
                        let viewControllerYouWantToPresent = self.storyboard?.instantiateViewController(withIdentifier: "pass1") as! ViewControllerngodetails

                        viewControllerYouWantToPresent.temp1 = self.id

                        self.present(viewControllerYouWantToPresent, animated: true, completion: nil)
                    }

                    self.alert.addAction(self.action)

                    self.present(self.alert, animated: true, completion: nil)
                }



            }




        }catch let error {
            print(error)
        }



    }
    task.resume()

        }

每个UI更新都必须在主线程上:

@IBAction func loginbutton(_ sender: Any) {
    let myUrl = NSURL(string: "http://www.shreetechnosolution.com/funded/ngo_login.php")

    let request = NSMutableURLRequest(url:myUrl! as URL)

    request.httpMethod = "POST"// Compose a query string

    let postString = "uname=\(textfieldusername.text!)&password=\(textfieldpassword.text!)";

    request.httpBody = postString.data(using: String.Encoding.utf8)



    let task = URLSession.shared.dataTask(with: request as URLRequest){ data , response , error in

    if error != nil
    {
        DispatchQueue.main.async {
            let alert = UIAlertController(title: "Alert Box !", message: "Login Failed", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
            // Present Alert Controller
            self.present(alert, animated: true, completion: nil)
        }
        return
    }

        // You can print out response object
        print("*****response = \(String(describing: response))")

        let responseString = NSString(data: data! , encoding: String.Encoding.utf8.rawValue )

        if ((responseString?.contains("")) == nil) {
            print("incorrect - try again")
            DispatchQueue.main.async {
                let alert = UIAlertController(title: "Try Again", message: "Username or Password Incorrect", preferredStyle: .alert)
                let yesAction = UIAlertAction(title: "Nochmalversuchen", style: .default) { (action) -> Void in }

                // Add Actions
                alert.addAction(yesAction)

                // Present Alert Controller
                self.present(alert, animated: true, completion: nil)
            }
        }

        else {
            print("correct good")
        }

        print("*****response data  = \(responseString!)"

        do {
            //create json object from data

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

                if let email = json["UserName"] as? String,
                    let password1 = json["passowrd"] as? String {

                    print ("Found User id:  called \(email)")
                }
                let msg = (json.value(forKey: "message") as! NSString!) as String
               let id = (json.value(forKey: "NgoId") as! NSString!) as String

                DispatchQueue.main.async {
                    self.alert = UIAlertController(title: "Alert Box!", message: "\(msg)", preferredStyle: .alert)
                    print("the alert\(self.alert)")
                    self.action = UIAlertAction(title: "OK", style: .default) { (action) -> Void in
                        let viewControllerYouWantToPresent = self.storyboard?.instantiateViewController(withIdentifier: "pass1") as! ViewControllerngodetails

                        viewControllerYouWantToPresent.temp1 = self.id

                        self.present(viewControllerYouWantToPresent, animated: true, completion: nil)
                    }

                    self.alert.addAction(self.action)

                    self.present(self.alert, animated: true, completion: nil)
                }



            }




        }catch let error {
            print(error)
        }



    }
    task.resume()

        }

这不是Swift 3.x SYNTAX这不是Swift 3.x SYNTAX请不要将您的机密信息放在此处作为基本URL而不是此,您可以编写。请不要将您的机密信息放在此处作为基本URL而不是此,您可以编写