ds753947 2016-04-25 10:29
浏览 73
已采纳

Swift 2 php mysql注册问题

I'm fairly new to programming with Swift in Xcode so I have been recently following the fantastic php sql sign up tutorial by Sergey Kargopolov located here http://swiftdeveloperblog.com/store-user-information-in-mysql-database/.

Unfortunately the tutorial was slightly outdated and needed to be updated for Swift 2.0. I managed to substitute the problematic code by implementing a do/catch statement which seems to work great except when i receive a response from the server side php script I can't seem to navigate to different view controllers based on the result. For example if the response is "Registration Successful" the user is directed to the protected page however if the email address already exists in the database, I want it to stay on the same page.

Currently I have the code working to the point where the alert appears (either user already exists or successful) but when the user clicks "Ok", they are directed to the protected page regardless of the result. I figured it would be a simple case of telling it to go to the next view based on the result in this "if" statement:

    if (resultValue == "Success") {

    isUserRegistered = true 

    let next = self.storyboard?.instantiateViewControllerWithIdentifier("ProtectedViewController") as! ProtectedViewController
    self.presentViewController(next, animated: true, completion: nil)
    }

but it doesn't seem to work. Hopefully it makes sense what i'm trying to do and any help is greatly appreciated.

here is my code:

                let myUrl = NSURL(string: "http://localhost/PhpProject1/scripts/registerUser.php")
                let request = NSMutableURLRequest(URL: myUrl!)
                request.HTTPMethod = "POST"

                let postString = "userEmail=\(userEmail!)&userFirstName=\(userFirstName)&userLastName=\(userLastName)&userPassword=\(userPassword!)"

                request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);

                let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {

                    data, response, error in

                    if error != nil {

                        print("error=\(error)")

                        return

                    }

                    do {

                        let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary

                        if let parseJSON = json {

                            var resultValue = parseJSON["status"] as! String!

                            print("result: \(resultValue)")

                            var isUserRegistered: Bool = false


                            if (resultValue == "Success") {

                                isUserRegistered = true

                            }

                            var messageToDisplay: String = parseJSON["message"] as! String!

                            if (!isUserRegistered)

                            {

                                messageToDisplay = parseJSON["message"] as! String!

                            }

                            dispatch_async(dispatch_get_main_queue(), {

                                var myAlert = UIAlertController(title: "Alert", message: messageToDisplay, preferredStyle: UIAlertControllerStyle.Alert)

                                let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default) { action in

//                            self.dismissViewControllerAnimated(true, completion: nil)
                                let next = self.storyboard?.instantiateViewControllerWithIdentifier("ProtectedViewController") as! ProtectedViewController
                                self.presentViewController(next, animated: true, completion: nil)

                                }

                                myAlert.addAction(okAction)

                                }

                            )}

                    } catch { print(error)}

                }

                task.resume()

            }

            func displayAlertMessage(userMessage:String) {

                let myAlert = UIAlertController(title: "Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.Alert);

                let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)

                myAlert.addAction(okAction);

                self.presentViewController(myAlert, animated: true, completion: nil)

            }
        }

I should also add that when the user registers successfully, I get "Result: 200" in the output window but when the user email already exists I get "Result: 400". I just don't know how to take advantage of this.

Thanks in advance!

  • 写回答

2条回答 默认 最新

  • drui0508 2016-04-25 15:08
    关注

    Well, I stayed up a little longer and thanks to you Scriptable I was able to figure it out.

    Basically all I did was create a new variable:

    var statuscheck: Int!
    

    And then after the "if let parseJSON = json {" statement I cast the "status" as an Int like this:

    self.statuscheck = (parseJSON["status"]! as! NSString).integerValue
    

    Then after the line beneath the "dispatch_async(dispatch_get_main_queue()":

    let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default) { action in
    

    I did the check:

    if (self.statuscheck == 200) {
         let next = self.storyboard?.instantiateViewControllerWithIdentifier("ProtectedViewController") as! ProtectedViewController
         self.presentViewController(next, animated: true, completion: nil)
    }
    

    This seems to work great now.

    Thanks again for all your help Scriptable. You definitely pointed me in the right direction!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的