spinnerView在appdelegate中无效

时间:2016-06-20 06:34:28

标签: ios iphone xcode swift progress-bar

你好我在这里使用appdeligate一些特定的方法,如登录应用程序和从应用程序注销。 我在这里有一个代码 目前正在发挥作用,但问题是当登录请求发送到服务器然后微调器视图不起作用

http://lms.dev/course/2/test

此处下一步是登录功能

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.
    spinnerInitialization();
     email = NSUserDefaults.standardUserDefaults().stringForKey("email")\\Getting Email from local storage 
     password = NSUserDefaults.standardUserDefaults().stringForKey("password")\\\\Getting Password from local storage
    if ((email == nil) && (password == nil)){

    }
    else if ((email == "") && (password == "")) {

   }
    else {
        loginRequest(email!, password: password!)
    }

    return true

}

接下来是旋转器功能

    func loginRequest( var email: String,password: String){

    let request = NSMutableURLRequest(URL: NSURL(string: "www.example.com/login")!)
    request.HTTPMethod = "POST"
    let postString = "email=\(email)&password=\(password)&token=\("ttttttt")"

    dispatch_async(dispatch_get_main_queue()) {
        self.startSpinner()
    }

    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
        data, response, error in
        if(error != nil){

            let nsError = error! as NSError
            let dialog = UIAlertController(title: "Internal Server Error?", message: nsError.localizedDescription, preferredStyle: UIAlertControllerStyle.Alert);

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

                print("Ok Button Action ")
            }

            dialog.addAction(okAction);

            dispatch_async(dispatch_get_main_queue(), {
                //Code that presents or dismisses a view controller here
                self.window?.rootViewController?.presentViewController(dialog, animated: true, completion: nil)
            })
        }

        else{
        do {
            let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)

            let status  = json["status"]as? Int
            let message = json["message"]as? String

            if(status == 0){


                let dialog = UIAlertController(title: "Login Unsuccessful?", message: message, preferredStyle: UIAlertControllerStyle.Alert);

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

                    print("Ok Button Action ")
                }

                dialog.addAction(okAction);

                dispatch_async(dispatch_get_main_queue(), {

                    self.window?.rootViewController?.presentViewController(dialog, animated: true, completion: nil)

                })


            }
            else
            {
                let newModel = UserDetails()
                let result = json["data"]
                let userId = result!!["id"] as? String
                let companyId = result!!["companyId"] as? String
                let name = result!!["name"] as? String
                let companyName = result!!["companyName"] as? String
                email = (result!!["email"] as? String)!
                let userType = result!!["userType"] as? String

                NSUserDefaults.standardUserDefaults().setObject(email, forKey: "email")
                NSUserDefaults.standardUserDefaults().setObject(userId, forKey: "userId")
                NSUserDefaults.standardUserDefaults().setObject(companyId, forKey: "companyId")
                NSUserDefaults.standardUserDefaults().setObject(name, forKey: "name")
                NSUserDefaults.standardUserDefaults().setObject(companyName, forKey: "companyName")
                NSUserDefaults.standardUserDefaults().setObject(userType, forKey: "userType")
                NSUserDefaults.standardUserDefaults().setObject(password, forKey: "password")
                NSUserDefaults.standardUserDefaults().setObject("afdg2015", forKey: "token")

                newModel.userId = userId!
                newModel.companyId = companyId!
                newModel.userName = name!
                newModel.companyName = companyName!

                if userType == "0"{
                    newModel.asEmployeer = true
                    NSUserDefaults.standardUserDefaults().setObject("true", forKey: "asEmployeer")
                    NSNotificationCenter.defaultCenter().postNotificationName("load", object: nil)
                }
                else {
                    newModel.asEmployeer = false
                    NSUserDefaults.standardUserDefaults().setObject("false", forKey: "asEmployeer")
                    NSNotificationCenter.defaultCenter().postNotificationName("load", object: nil)
                }

                self.userDetails.append(newModel)

                dispatch_async(dispatch_get_main_queue()) {

                    let storyboard = UIStoryboard(name: "Main", bundle: nil)
                    var scheduleController = storyboard.instantiateViewControllerWithIdentifier("scheduleHome100")
                    if (newModel.asEmployeer == false){
                    //EmployeeScheduleViewController
                         scheduleController = storyboard.instantiateViewControllerWithIdentifier("EmployeeScheduleViewController")
                    }

                    let drawerViewController = storyboard.instantiateViewControllerWithIdentifier("DrawerViewController")

                    let leftSideNav = UINavigationController(rootViewController: drawerViewController)
                    let centerNav = UINavigationController(rootViewController: scheduleController)

                    self.centerContainer = MMDrawerController(centerViewController: centerNav, leftDrawerViewController: leftSideNav)
                    self.centerContainer!.openDrawerGestureModeMask = MMOpenDrawerGestureMode.PanningCenterView;
                    self.centerContainer!.closeDrawerGestureModeMask = MMCloseDrawerGestureMode.PanningCenterView;

                    self.window!.rootViewController = self.centerContainer
                    self.window!.makeKeyAndVisible()
                }
            }

        } catch {
            print("error serializing JSON: \(error)")
        }
            dispatch_async(dispatch_get_main_queue(), {
                self.stopSpinner()
            })
        }
    }

    task.resume();
}

更新 当我从ViewController发送请求时,如

func startSpinner(){
    print("In startSpinner Function")
    view.addSubview(spinnerView)
}

func stopSpinner(){
    print("In stopSpinner Function")
    let subViews = view.subviews
    for subView in subViews{
        if subView.tag == 1000{
            subView.removeFromSuperview()
        }

    }
}

func spinnerInitialization(){
    print("In spinnerInitialization Function")
    spinnerView = UIView(frame: CGRect(x:0, y:0,width: 250,height: 50))
    spinnerView.backgroundColor = UIColor.blackColor()
    spinnerView.layer.cornerRadius = 10
    let wait = UIActivityIndicatorView(frame: CGRect(x:0,y: 0,width: 50,height: 50))
    wait.color = UIColor.whiteColor()
    wait.hidesWhenStopped = false
    wait.startAnimating()
    let text = UILabel(frame: CGRect(x:60,y:0,width:200,height: 50))
    text.textColor = UIColor.whiteColor()
    text.text = "Please wait..."
    spinnerView.addSubview(wait)
    spinnerView.addSubview(text)
    spinnerView.center = view.center
    spinnerView.tag = 1000
}

然后微调器显示

请帮我解决这个问题 谢谢

1 个答案:

答案 0 :(得分:0)

您正在执行dataTaskWithRequest这是异步过程。您必须添加一个完成处理程序,以便您的函数等到该过程完成,如下所示:

    func loginRequest( var email: String,password: String ,complete: (evalSuccess: Bool) -> ()){

///Your code:

     if(status == 0){


                    let dialog = UIAlertController(title: "Login Unsuccessful?", message: message, preferredStyle: UIAlertControllerStyle.Alert);

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

                        print("Ok Button Action ")
                    }

                    dialog.addAction(okAction);

                    dispatch_async(dispatch_get_main_queue(), {

                        self.window?.rootViewController?.presentViewController(dialog, animated: true, completion: nil)

                    })


                }
                else
                {
                  complete(evalSuccess: True)
                    let newModel..
               ///your code

             }

然后在appDelegate中调用它:

loginRequest(youremail, yourpassword){success in
if success{
//Do something
}

}