如何根据远程服务器的响应以编程方式从另一个视图控制器调用视图控制器

时间:2015-03-16 12:39:22

标签: swift uiviewcontroller viewcontroller

在我的应用程序中,我在主视图控制器(loginViewController.swift)中获取服务器凭据。当我点击'loginViewController'上的'Login'按钮时,它会显示app logoViewController,它具有活动指示器视图,并且凭证值通过https连接传递给远程服务器。我在远程服务器的响应中得到一个JSON数组,其中包含消息“Successful:1”或“Unsuccessful:0”以及其他应用程序详细信息。

对于JSON数组中的值'1',我想显示menuViewController屏幕,对于值'0',我想显示RegisterViewController屏幕,以便在应用程序中进一步处理。

调用'menuViewController'/'RegisterViewController'应该在'logoViewController'的后台进程中进行。

如果已经尝试过以下代码,但无法调用'menuViewController'/'RegisterViewController'。

如果我出错了,请告诉我。 UIStoryboard方法是对的吗? 任何建议或链接或教程都会有所帮助。

import UIKit

class logoViewController: UIViewController {

    @IBOutlet weak var act: UIActivityIndicatorView!
    override func viewDidLoad() {
        super.viewDidLoad()

        self.act.startAnimating()



        // Do any additional setup after loading the view.
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // syncreq function is called from the connectionViewController.
    // connectionViewController is the common class for connecting to the remote server  
    func syncreq (JSONdata: AnyObject) { // Proceesing for PRMS response


       // Getting the value from the JSON
        var Successful = self.getIntFromJSON(JSONdata as NSDictionary, key: "Successful")


        println("Value of Successful : \(Successful)")

        if (Successful == 0){


            //let secondViewController = self.storyboard?.instantiateViewControllerWithIdentifier("registrationID") as regVC

            //self.navigationController?.pushViewController(secondViewController, animated: true)
            //performSegueWithIdentifier("registrationID", sender: self)


            let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
            var setViewController = mainStoryboard.instantiateViewControllerWithIdentifier("registrationID") as RegisterViewController
            self.presentViewController(setViewController, animated: false, completion: nil)

        }
        else if (Successful == 1){
             let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
            var setViewController = mainStoryboard.instantiateViewControllerWithIdentifier("mnuID") as menuViewController
            self.presentViewController(setViewController, animated: false, completion: nil)
        }



    }

    func getIntFromJSON(data: NSDictionary, key: String) -> Int {

        let info : AnyObject? = data[key]
        // println("Value of data[key] : \(key)")

        if let info = data[key] as? Int {
            println("Value of value for \(key) : \(info)")
            return info
        }

        else {
            return 0

        }

    }

}

提前致谢

1 个答案:

答案 0 :(得分:1)

我已经实现了一个通用函数,它将回调来自远程服务器的响应的调用函数。

以下是我实施的功能。

func connect(jsonString:NSDictionary) -> NSDictionary
{



            var JSONdata: AnyObject = ["" : ""] as Dictionary<String, String>

            println("------------------Function connserv")

            let prefs = NSUserDefaults.standardUserDefaults()


    var conn_timeout: AnyObject = prefs.objectForKey("conn_timeout")!
    var numberFormatter = NSNumberFormatter()
    var number:NSNumber? = numberFormatter.numberFromString(conn_timeout as! String)
    if let number = number {
        var integer = Int(number)
        println("\(integer)")
    }
            var recon_maxcount: AnyObject = prefs.objectForKey("recon_maxcount")!
    println("recon_maxcount in Connection : \(recon_maxcount)")
    println("conn_timeout in Connection : \(conn_timeout)")
    var recon_interval: AnyObject = prefs.objectForKey("recon_interval")!
    println("recon_interval in Connection : \(recon_interval)")
    var number1:NSNumber? = numberFormatter.numberFromString(recon_maxcount as! String)
    if let number1 = number1 {
        var integer1 = Int(number1)
        println("\(integer1)")
    }
    var number2:NSNumber? = numberFormatter.numberFromString(recon_interval as! String)
    //if let number2 = number2 {
        var integer2 = Int(number2!)
    var xval = UInt32(integer2)
        println("\(xval)")
    //}

            var IP: AnyObject = prefs.objectForKey("IP")!
            var port: AnyObject = prefs.objectForKey("Port")!
            println("IP in Connection : \(IP)")
            println("port in Connection : \(port)")
            prefs.synchronize()

            println("HTTP request jsonString : \(jsonString)")

            var request = NSMutableURLRequest(URL: NSURL(string: "https://\(IP):\(port)/")!)
    var response: NSURLResponse?
    var error: NSError?
    request.HTTPBody = NSJSONSerialization.dataWithJSONObject(jsonString, options: nil, error: &error)
    request.timeoutInterval = (number as! NSTimeInterval)
    request.HTTPMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    //request.setValue("application/json", forHTTPHeaderField: "Accept")
    request.addValue("gzip", forHTTPHeaderField: "Accept-encoding")
    println("Firing synchronous url connection......")
    println(request)
          //println("Before======\(i)!")
    for (var i = 0; i < number1 as! Int ; i++)
    {
        var error: NSError?
        println("Try connecting to server: \(NSDate())")

        let urlData = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)
        //println("response : \(response)")
        //println("error : \(error)")

        if error != nil || urlData!.length == 0
        {
            println("Error happend timeout======\(error?.code)!")
            println(NSDate())

            sleep(xval as UInt32)
            //println("NSDate()")
            JSONdata = ["0" : "0"] as Dictionary<String, String>
            continue
        }
        else
        {
            println("Successfully connected : \(NSDate())")
            println("\(urlData!.length) bytes of data was returned")
            println(response!);
            if let httpResponse = response as? NSHTTPURLResponse {
                println("Status Code ------------------------------------>\(httpResponse.statusCode)")
            }
            println(NSString(data: urlData!, encoding: NSUTF8StringEncoding)!)
            var er: NSError?

            let JSONresdata: AnyObject = (NSJSONSerialization.JSONObjectWithData(urlData!, options: .MutableContainers,error: &er)!)
             println("==========================================================================================")
            println("JSON response : \(JSONresdata)")
            JSONdata = JSONresdata as! NSDictionary
            break

        }
    }
     println("out of for loop : \(JSONdata)")
    return JSONdata as! NSDictionary;

}