ios - 解包时发现 nil 和可选值

标签 ios swift

当我单击登录按钮以从我的登录 View Controller 登录到我的 Web 服务时出现展开错误。我在登录 View Controller 中设置了两个文本字段和一个按钮。我不知道我出了什么问题.我评论了我收到以下错误的行

这是我的登录 View Controller

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()
}

}

任何帮助,请。

最佳答案

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

尝试放入 viewDidLoad api = AccountAPI()

关于ios - 解包时发现 nil 和可选值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29072483/

相关文章:

ios - 如何检测设备 iOS 版本构建号,(例如 13A452)

ios - 如何使用 NSCache 并从 Url 下载图像并在 CollectionViewCell 中显示图像?

ios - 使用 Firebase 添加好友系统的最佳实践?

IOS - 如何使用来自不同 XIB 文件的多个 ViewController 创建 UIPageViewController

ios - 我试图为我的应用程序实现启动画面,因为它需要从 api 将数据加载到应用程序中

ios - 用户首次启动应用程序时显示教练标记 View Swift 3

ios - Xcode 错误 ITMS 90096 - 我没有使用任何启动屏幕

swift - 带有 NsurlConnection 的 UIViewActivityIndi​​cator 不会快速停止动画

android - 相当于 Xcode 中的 android 的 styles.xml

ios - 无法使用 swift 类型的参数列表调用方法