swift modal segue,prepareForSegue multithreading

时间:2014-11-10 05:30:05

标签: multithreading swift segue

我试图在swift

中制作一个segue(现在的模态segue)

我调用此函数(发件人是一个按钮(登录按钮))

    func getUserAndSave(sender: AnyObject )
{
    var request = NSMutableURLRequest(URL: NSURL(string: GET_USER_API))
    var session = NSURLSession.sharedSession()
    request.HTTPMethod = "POST"

    var hash = NSUserDefaults.standardUserDefaults().valueForKey("hash") as String
    var token = NSUserDefaults.standardUserDefaults().valueForKey("token") as String


    var params = ["hash":hash, "token":token] as Dictionary<String, String>

    var err: NSError?
    request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")


    getUser(request) { result in
        switch result
            {
        case let .Error(error):
            print(error)
            // display error message

        case let .Value(boxedUser):
            let user = boxedUser.value
            self.user = user;
            dispatch_async(dispatch_get_main_queue())
            {
                    self.performSegueWithIdentifier("show user details", sender: sender)
            }

            // do something with user
        }
    }

}

这是getUser函数的实现(整个swift文件)的主要内容 这段代码是getUser函数:

typealias JSON = AnyObject
typealias JSONDictionary = Dictionary<String, JSON>
typealias JSONArray = Array<JSON>

final class Box<A> {
let value: A

init(_ value: A) {
    self.value = value
}
}

enum Result<A> {
case Error(NSError)
case Value(Box<A>)
}

enum Gender
{
case FEMALE , MALE

var description : String
{
    switch self
    {
        case .FEMALE: return "FEMALE";
        case .MALE: return "MALE";
    }
}
}

struct User
{
var fullName : String
var email : String
var raking : Int
var gender : Gender
}




func getUser(request: NSURLRequest, callback: (Result<User>) -> ()) {
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, urlResponse, error            in
    // if the response returned an error send it to the callback
    if let err = error {
        callback(.Error(err))
        return
    }

    var jsonErrorOptional: NSError?
    let jsonOptional: JSON! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0), error: &jsonErrorOptional) as? NSDictionary

    // if there was an error parsing the JSON send it back
    if let err = jsonErrorOptional {
        callback(.Error(err))
        return
    }
    if let json = jsonOptional as? JSONDictionary
    {
        if let userDic = json["user"] as? NSDictionary
        {
            var fullName = userDic["fullName"] as AnyObject? as? String
            var email = userDic["email"] as AnyObject? as? String
            var ranking = userDic["ranking"] as AnyObject? as? Int
            var tmpGender = userDic["gender"] as AnyObject? as? Int

            var gender : Gender = tmpGender == 1 ?  Gender.FEMALE : Gender.MALE;

            let user = User(fullName: fullName!, email: email!, raking: ranking!, gender: gender);
            callback(.Value(Box(user)))

        }
    }
    callback(.Error(NSError()))
}
task.resume()
}

它不会在主线程中被调用

这就是我调用getUser函数的方法

        getUser(request) { result in
        switch result
            {
        case let .Error(error):
            print(error)
            // display error message

        case let .Value(boxedUser):
            let user = boxedUser.value
            self.user = user;
            dispatch_async(dispatch_get_main_queue())
            {
                    self.performSegueWithIdentifier("show user details", sender: sender)
            }

            // do something with user
        }

这是我的prepareForSegue函数:

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
            if(segue.identifier == "show user details")
            {
                if((sender?.isKindOfClass(LogInViewController)) != nil)
                {
                    if(segue.destinationViewController.isKindOfClass(UserInfoViewController))
                    {
                        var sourceVC = sender as LogInViewController
                        var destinationVC = segue.destinationViewController as UserInfoViewController

                        if(self.user != nil)
                        {
                            destinationVC.user = self.user;
                        }
                        else
                        {
                            print("WARNING!: self.user is NIll");
                        }
                    }
                }
            }
}

当我开始准备segue功能时,应用程序崩溃了! ,我试图发送自己(LogInViewController),它也崩溃,在调试器,它卡在第一行 prepareForsegue函数,这段代码有什么问题? 对不起长代码:D

0 个答案:

没有答案