Swift 3.0 iOS10通过Firebase的segue发送方传递异步数据

时间:2017-04-25 14:30:24

标签: ios json swift asynchronous uistoryboardsegue

我有一个登录页面,用于收集用户名和密码。在提交时,它发送到数据库以检索我们的服务器访问密钥。我通过使用session.dataTask的异步JSON POST来完成此操作。当我检索JSON对象时,我解析了它的密钥。我想将它传递到下一页,检索一个firebase令牌,然后将两个数据片段发送回服务器以进行数据库存储。我创建了一个“准备segue”函数,它收集变量并将其传递给下一页的变量。我相信我没有正确设置事件序列,或者数据没有从Async容器中删除。有人可以看看这两个文件,看看我错了吗?

这是我想在进行REST Web服务调用之后离开的第一页......

loginVC.swift:

import UIKit

class LoginVC: UIViewController {

    @IBOutlet weak var username: UITextField!
    @IBOutlet weak var password: UITextField!
    @IBOutlet weak var validationBox: UITextView!
    @IBAction func logInAction(_ sender: UIButton) {
        guard let user = username.text, !user.isEmpty else {
            validationBox.text = "Please enter valid credentials"
            return
        }
        guard let pass = password.text, !pass.isEmpty else {
            validationBox.text = "Please enter valid credentials"
            return
        }

        let params = ["sUser": username.text!, "sPass": password.text!]

        let url = URL(string: "restWebServiceURL")!
        let session = URLSession.shared
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        do {
            request.httpBody = try JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
        } catch let error {
            print(error.localizedDescription)
        }
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in

            guard error == nil else { return }
            guard let data = data else { return }

            do {
                if let parsedJSON = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
                    let parsedData = parsedJSON["d"] as! [String:Any]
                    let key = parsedData["key"] as! String
                    DispatchQueue.main.async {
                        print(key)
                        self.performSegue(withIdentifier: "FirebaseVC", sender: key)
                    }

                }
            } catch let error {
                print(error.localizedDescription)
            }
        })
        task.resume()
    }
    func sayHello() {
        print("Hello!")
    }
    func sayGoodbye() {
        print("Goodbye!")
    }



    override func viewDidLoad() {
        super.viewDidLoad()
        validationBox.text = "Ready..."
        func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            if let FirebaseInit = segue.destination as? FirebaseVC {
                if let sKey = sender as? String {
                    print("prepare - " + sKey)
                    FirebaseInit.sessionKey = sKey
                }
            }
        }
    }

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


}

这是我想要接收数据访问密钥的页面......

FirebaseVC.swift:

import UIKit

class FirebaseVC: UIViewController {

    private var _sessionKey = String()

    var sessionKey : String {
        get { return _sessionKey }
        set { _sessionKey = newValue }
    }

    @IBOutlet weak var sessionKeyTestBox: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()
        print(_sessionKey)

    }

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



}

随意建议一种更好的方法将数据传递到下一页。感谢...

1 个答案:

答案 0 :(得分:1)

事实证明,在我的假设中,事件链是关闭的我是正确的。按照@achrefGassoumi建议的模型,我将数据任务移到了Singleton服务:

import Foundation

struct CallWebService {

    static let sharedInstance = CallWebService()

    func logInToCaduceus(u: String, p: String, completion: @escaping (_ sKey: String) -> ()) {
        let params = ["sUser": u, "sPass": p]

        let url = URL(string: "https://telemed.caduceususa.com/ws/telemed.asmx/telemedLogin")!
        let session = URLSession.shared
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        do {
            request.httpBody = try JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
        } catch let error {
            print(error.localizedDescription)
        }
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in

            guard error == nil else { return }
            guard let data = data else { return }

            do {
                if let parsedJSON = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
                    let parsedData = parsedJSON["d"] as! [String:Any]
                    let key = parsedData["key"] as! String
                    DispatchQueue.main.async {
                        completion(key)
                    }
                }
            } catch let error {
                print(error.localizedDescription)
            }
        })
        task.resume()

    }

}

然后我的两个控制器看起来像这样:

LoginVC

import UIKit

class LoginVC: UIViewController {

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if (segue.destination.isKind(of: FirebaseVC.self)) {
            let vc = segue.destination as! FirebaseVC
            if let sKey = sender as? String {
                vc.sessionKey = sKey
            }
        }
    }

    @IBOutlet weak var username: UITextField!
    @IBOutlet weak var password: UITextField!
    @IBOutlet weak var validationBox: UITextView!
    @IBAction func logInAction(_ sender: UIButton) {
        guard let user = username.text, !user.isEmpty else {
            validationBox.text = "Please enter valid credentials"
            return
        }
        guard let pass = password.text, !pass.isEmpty else {
            validationBox.text = "Please enter valid credentials"
            return
        }

        CallWebService.sharedInstance.logInToCaduceus(u: username.text!, p: password.text!, completion: {(sessionKey: String) -> Void in
                print(sessionKey)
                self.performSegue(withIdentifier: "FirebaseVC", sender: sessionKey)
            }
        )

    }

    override func viewDidLoad() {
        super.viewDidLoad()
        //validationBox.textAlignment = .center
        validationBox.text = "Ready..."
    }

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


}

和接收FirebaseVC

import UIKit

class FirebaseVC: UIViewController {

    private var _sessionKey = String()

    var sessionKey : String {
        get { return _sessionKey }
        set { _sessionKey = newValue }
    }

    @IBOutlet weak var sessionKeyTestBox: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()
        sessionKeyTestBox.text = _sessionKey
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

请原谅我的(非快速)Javascript术语,但基本上我将数据调用移动到服务中,然后使用完成方法在服务中放置一个回调方法,以确保在收到数据之前不会触发performSegue并解析出来。因此,当我将表单数据提交给服务器时,在异步调用完成之前,segue不会触发。