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

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
    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!

    点赞 评论
  • doushang7209
    doushang7209 2016-04-25 13:32

    From what I can see from your JSON response, parseJSON["status"] is the HTTP statusCode, which is a numerical status code. 200 being success, 400 being bad request, 404 being Not found, 500 being an error.

    You could either read the message from the dictionary instead or depending on how your PHP code is working you could cast the status as an Integer and only segue when status is 200. For any other status code you likely want to show the message to the user.

    This depends on whether you are intentionally returning status codes based on the result, for example a status code of 401 is un-authorised.

    Using the status code properly would be much more reliable than comparing strings.

    EDIT:

    import Foundation
    
    let jsonData = "{ \"message\": \"Successfully registered new user\", \"status\": 200, \"userEmail\": \"abc\", \"userFirstName\": \"a\", \"userId\": 22, \"userLastName\": \"a\" }".dataUsingEncoding(NSUTF8StringEncoding)
    
    do {
    
        let json = try NSJSONSerialization.JSONObjectWithData(jsonData!, options: .MutableContainers) as? NSDictionary
    
        if let parseJSON = json {
            let statusCode = parseJSON["status"] as! Int
    
            switch statusCode {
            case 200:
                print("successfully logged in")
            case 400, 401:
                print("access denied")
            default:
                print("error occurred")
            }
        }
    }
    

    Above, I have added an example of how you might approach this in Swift, you just need to change the behaviour depending on which statusCodes you want to deal with and how

    点赞 评论

相关推荐