Swift - 等到函数完成

时间:2014-07-15 21:18:14

标签: ios function swift xcode6

我有一个应用程序需要一个人登录才能获得访问权限。为此,我创建了一个API来检索和存储数据库中的数据。例如,我创建了一个来检查并查看输入的用户名和密码是否正确。唯一的问题是,我用来检索数据的函数很慢。它不会及时返回检查系统的数据,以查看用户名和密码是否正确。

class LoginViewController: UIViewController {

var statusCode = Int()
var returnedName = String()

@IBOutlet var usernameField: UITextField
@IBOutlet var passwordField: UITextField

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

    @IBAction func loginAction(sender: AnyObject) {

    var invalidLoginAlert = UIAlertView(title: "Invalid Username/Password", message: "Please input a correct Username or Password", delegate: nil, cancelButtonTitle: "Dismiss")

    var noInfoLoginAlert = UIAlertView(title: "Invalid Username/Password", message: "Please input a Username and Password to Proceed", delegate: nil, cancelButtonTitle: "Dismiss")

    usernameField.resignFirstResponder()
    passwordField.resignFirstResponder()

    if usernameField.text != "" && passwordField.text != "" {
        login(usernameField.text.lowercaseString, password: passwordField.text.lowercaseString)
        sleep(2)
        if statusCode == 300 {
            println("Login Success")
            let MainView = self.storyboard.instantiateViewControllerWithIdentifier("MainView") as MainViewController
            self.presentViewController(MainView, animated: true, completion: nil)
        }
        else {
            invalidLoginAlert.show()
            println("Login Failed")
        }
    }
    else {
        noInfoLoginAlert.show()
        println("Cannot Login, Invalid Information")
    }
}

如上所述,我必须使用sleep()函数来减慢功能。这并不总是有效,因为在不同的地方连接速度较慢(加载时间可能超过2秒)EX - 3G和LTE或慢速WiFi。

函数Login(username:string,password:string)返回一个代码,用于确定用户名和密码是否正确。如果它们都是正确的,它将返回代码300,否则它将返回400.

有没有办法可以创建一个didFinishLoading()函数,返回一个bool,检查并查看login()函数中的信息是否已加载?这样,他们的连接是否缓慢无关紧要。

布雷克

编辑:这是我的网络代码:

func login(username: String, password: String){

    // Now escape anything else that isn't URL-friendly
    var usernameID = username.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
    var passwordID = password.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)

    var urlPath = "http://www.example.com"
    var url: NSURL = NSURL(string: urlPath)
    var session = NSURLSession.sharedSession()
    var task = session.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in
        var err: NSError?
        var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary

        var name: String? = jsonResult["data"] as String?;
        var code: Int = jsonResult["status"] as Int;

        self.statusCode = code
        println(self.statusCode)
        })
    task.resume()
}

1 个答案:

答案 0 :(得分:1)

在您的完成处理程序中 - 您正在计算jsonResult - 您应该通知您的视图控制器已经或者没有收到用户名和密码。