swift http post json + 登录

 var nsUrl : NSURL = NSURL(string:API_HOST+"/"+LOGIN_API)!

        var request = NSMutableURLRequest(URL:nsUrl)

        request.HTTPMethod = "POST"

        var postKeyJson : NSString = "\(LOGINPOSTKEY)"+"="+"{\"email\":\"\(username)\",\"password\":\"\(userpass)\"}"

        request.HTTPBody = NSString(format: postKeyJson).dataUsingEncoding(NSUTF8StringEncoding)

        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response:NSURLResponse!,data:NSData!,error:NSError!) -> Void in

            if error != nil{

                println(error)

                var alert = UIAlertView(title: "提示", message:"请求发生错误,可能是网络未连接,请检查", delegate: self, cancelButtonTitle: "好的")

                alert.show()

                return

            }

            //var result = NSString(data: data, encoding: NSUTF8StringEncoding)

            // swiftyJSON

            var jsonResult = JSON(data: data!)

            // traditional method

            //var jsonResult : NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary

            //println(jsonResult)

            

            // 1 username is not exist; 2 password is wrong;  0 success

            if (jsonResult["result"] == 1) {

                var alert = UIAlertView(title: "提示", message:"用户名不存在!", delegate: self, cancelButtonTitle:"取消")

                alert.show()

                return

            }else if(jsonResult["result"] == 2) {

                var alert = UIAlertView(title: "提示", message:"密码错误!", delegate: self, cancelButtonTitle:"取消")

                alert.show()

                return

            }else if ((jsonResult["result"] == 0) && (jsonResult["access_token"] != nil)) {

                var alert = UIAlertView(title: "提示", message:"登录成功!", delegate: self, cancelButtonTitle:"确定")

                alert.show()

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

 

            }

        })

 

你可能感兴趣的:(swift)