在展开和可选值时找到零

时间:2015-03-16 08:34:01

标签: ios swift

当我点击登录按钮从我的登录视图控制器登录我的网络服务时,我有解包错误。我在登录视图控制器中设置了两个文本字段和一个按钮。我不知道我有什么问题。我评论了我收到以下错误的行

这是我的登录视图控制器

class SignInViewController: UIViewController{

@IBOutlet weak var userEmail: UITextField!
@IBOutlet weak var userPassword: UITextField!
@IBOutlet weak var signInButton: UIButton!

var api : AccountAPI?
var email : String?
var password : String?

override func viewDidLoad() {
    super.viewDidLoad()
    self.removeNavigationBarItem()

    // Force the device in portrait mode when the view controller gets loaded
    UIDevice.currentDevice().setValue(UIInterfaceOrientation.Portrait.rawValue, forKey: "orientation")

}

@IBAction func signInTapped(){

    println("Tapped")

// Error Occur After This Line
        api!.signIn(["email" : "example@gmail.com", "passwd" : "12345"], url: "http://localhost:8080/ws/xxx/xxx/xxxx") { (succeeded: String, msg: String) -> () in
            var alert = UIAlertView(title: "Success!", message: "Nothing!", delegate: nil, cancelButtonTitle: "Okay.")

            if(succeeded == "ok") {
                alert.title = "Success!"
            }
            else {
                alert.title = "Failed :("
            }
            // Move to the UI thread
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                // Show the alert
                alert.show()
            })
        }

}

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    self.removeNavigationBarItem()

    self.navigationController?.hidesBarsOnSwipe = false
    self.navigationController?.setNavigationBarHidden(false, animated: true)
}

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

override func shouldAutorotate() -> Bool {
    // Lock autorotate
    return false
}

override func supportedInterfaceOrientations() -> Int {

    // Only allow Portrait
    return Int(UIInterfaceOrientationMask.Portrait.rawValue)
}

override func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation {

    // Only allow Portrait
    return UIInterfaceOrientation.Portrait
}

}

这是我的帐户API

import Foundation
import UIKit

class AccountAPI{

func createStringFromDictionary(dict: Dictionary<String,String>) -> String {
    var params = String()
    for (key, value) in dict {
        params += "&" + key + "=" + value
    }
    return params
}

func signIn(params : Dictionary<String, String>, url : String, postCompleted : (succeeded: String, msg: String) -> ()) {

    var request = NSMutableURLRequest(URL: NSURL(string: url)!)
    var session = NSURLSession.sharedSession()
    request.HTTPMethod = "POST"

    var params2 = createStringFromDictionary(params)
    var paramsLength = "\(countElements(params2))"
    var requestBodyData = (params2 as NSString).dataUsingEncoding(NSUTF8StringEncoding)

    var err: NSError?
    request.HTTPBody = requestBodyData

    var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in

        var strData = NSString(data: data, encoding: NSUTF8StringEncoding)

        var err: NSError?
        var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary

        var msg = "No message"

        if(err != nil) {
            println(err!.localizedDescription)
            let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
            println("Error could not parse JSON: '\(jsonStr)'")
            postCompleted(succeeded: "not_ok", msg: "Error")
        }
        else {

            if let parseJSON = json {
                // Okay, the parsedJSON is here, let's get the value for 'success' out of it
                if let success = parseJSON["status"] as? String {
                    println("Succes: \(success)")
                    postCompleted(succeeded: success, msg: "Logged in.")
                }
                return
            }
            else {

                let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
                println("Error could not parse JSON: \(jsonStr)")
                postCompleted(succeeded: "not_ok", msg: "Error")
            }
        }
    })

    task.resume()
}

}

任何帮助,请。

2 个答案:

答案 0 :(得分:1)

我没有在任何地方看到api变量集。您应该在用户点击按钮之前进行设置,因为您需要强行展开它。或者,您可以验证api的值,并在执行api调用之前返回nil。

答案 1 :(得分:1)

api变量未初始化。您应该在用户点击签名按钮之前执行此操作。

尝试放入viewDidLoad api = AccountAPI()