如何通过另一个Swift类和文件的警报通知用户

时间:2017-03-28 17:29:41

标签: ios xcode swift3

我有一个连接到故事板的Settingsviewcontroller.swift文件和一个名为connectionapi.swift的单独文件。

现在,当用户单击checkbutton时,将根据connectionapi类中的API检查给定的用户名和密码。现在,当即时结果生成错误时,我想通过警告消息通知用户。我试图找出几天如何做到这一点,但我似乎无法找到它。我总是以错误结束。

有人可以帮我一些代码示例:

viewcontroler文件

//
//  ViewControllerSettings.swift
//

import Foundation
import UIKit


class ViewControllerSettings: UIViewController {
    @IBOutlet weak var tGebruikersnaam: UITextField!
    @IBOutlet weak var tCode: UITextField!
    @IBOutlet weak var AnimatedImage: UIImageView!
    @IBOutlet weak var lCopyright: UILabel!
    @IBOutlet weak var lStatus: UILabel!


    // declare a iCloud Store to save and load data from
    var iCloudStore:NSUbiquitousKeyValueStore!
    var userName:String = ""
    var password:String = ""

    let API = myAPI()


    @IBAction func didTapOpslaan(_ sender: Any) {
        if tGebruikersnaam.text == "" || tGebruikersnaam.text == nil || tCode.text == "" || tCode.text == nil {
            return
        }

        print("Lets check username and password against the api")

        let newUsername = "\(tGebruikersnaam.text!)"
        let newCode = "\(tCode.text!)"




        API.CheckUsernamePassword(username: newUsername, code: newCode)  {
            isValid in
            print(isValid)

            if isValid == true {

                DispatchQueue.main.async {
                    print("The credentials are correct")
                    self.ShowAnimationOk()
                }
            }else {
                DispatchQueue.main.async {
                    print("the credentials are wrong")
                    self.ShowAnimationNo()
                }
            }


        }

    }

//  Code removed     

}

API Swift文件

//
//  ConnectAPI.swift


import Foundation
import UIKit




class myAPI{

    let api_key = "b88a734f186sad"
    let baseurl = "https://xxxx:443/xxxx/api"

    func CheckUsernamePassword(username :String ,code:String, completion: @escaping (Bool)->() )  {


        let urlString = "\(self.baseurl)/accounts/validateusernamepassword.json?username=\(username)&password=\(code)&api_key=\(self.api_key)"

        let url = URL(string: urlString)
        URLSession.shared.dataTask(with:url!) { (data, response, error) in
            if error != nil {
                print("API | Error URLSession : \(error!)")
                completion(false)
            } else {
                do {
                    let parsedData = try JSONSerialization.jsonObject(with: data!, options: []) as! [String:Any]

                    print("----------")


                    if parsedData["validated"] != nil {
                        if "\(parsedData["validated"]!)" == "1" {
                            print("API JSON | validated = \(parsedData["validated"]!)")
                            print("API JSON | message   = \(parsedData["message"]!)")
                            completion(true)

                        }else {
                            print("Credential Check not valid")
                            print("API JSON | validated = \(parsedData["validated"]!)")
                            print("API JSON | message   = \(parsedData["message"]!)")
                            completion(false)

                        }


                    }else{
                        print("Json Parse error: \(parsedData)")

                        // Raise a Alert here
                    }


                } catch let error as NSError {
                    print("API | Error Parsing JSON \(error)" )


                      // Raise a Alert here
                      // main.showAlert(message: "API | Error Parsing JSON \(error)")

                      //A error occured when checking credentials, try again later.

                    completion(false)
                }
            }

            }.resume()

    }

1 个答案:

答案 0 :(得分:0)

我不确定你的问题是什么。我假设你有两个问题:

  1. 您不知道如何将API类的错误消息传递给 ViewControllerSettings类。
  2. 您不知道如何在iOS之前显示警报
  3. 如果是这样的话,那就看看吧。

    <强> 1。传递错误消息

    你可以看到完成块(例如@escaping(Bool) - &gt;())将在使用URLSession的dataTask完成函数checkUsernamePassword后调用:

    func CheckUsernamePassword(username :String ,code:String, completion: @escaping (Bool)->() )  { ... }
    

    如果成功,则调用值为true的块

    completion(true)
    

    在其他情况下,您使用值false调用

    completion(false)
    

    要传递更多信息(例如错误消息),您只需在完成块中添加输入参数即可。为每个名称添加更好的名称,以便更清楚。例如,将其更改为:

    ..., completion: @escaping (valid: Bool, errorMessage: String?) -> ())
    

    然后,如果API成功,则在没有errorMessage的情况下调用它:

    completion(valid: true, errorMessage: nil)
    

    如果它出现错误,您传递自己的错误消息或从NSError获取

    completion(valid: false, errorMessage: "Credential check not valid.")
    

    <强> 2。在UIAlertController中显示错误

    首先创建一个在ViewControllerSettings中显示标准警报的实用程序函数:

    // Simple Alert UI
    func showAlert(title: String, message: String) {
         let actionSheetController: UIAlertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
    
         // add close button
         let cancelAction: UIAlertAction = UIAlertAction(title: "Close", style: .cancel) { _ in }
         actionSheetController.addAction(cancelAction)
    
         // show on self
         self.present(actionSheetController, animated: true, completion: nil)
    }
    

    如果您执行了第一步,则可以在呼叫站点(ViewController)访问您的错误消息。

    当您调用API时,errorMessage可用,只需显示alert:

    // didTap...
    API.CheckUsernamePassword(username: newUsername, code: newCode)  {
       (isValid, errorMessage) in
        if isValid {
            ...
        } else {
            let error = errorMessage! // I don't recommend forced-casting though
            self.showAlert(title: "Error!", message: error) // show Alert UI
        }
    }