自定义协议Swift

时间:2017-03-21 17:07:24

标签: ios swift swift3 protocols

我有一个协议

Example x;

namespace whatever {
    Example y;
}

void foo() {
    static Example z;
}

我在主视图中调用了它

import UIKit
import Alamofire
import SwiftyJSON

protocol RequestProtocol: class {
    func RequestConnection(json: JSON, status: Int, Message: String)
}

class API: UIViewController {

    var delegate: RequestProtocol?
    var json: JSON = []

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

    func RequestConnection() {
        Alamofire.request(variablesClass.url).responseJSON { (response) -> Void in
            switch response.result {
            case .success:
                let result = response.result.value
                if response.response?.statusCode == 200 {
                    self.json = JSON(result!)
                    DispatchQueue.main.async(execute:  {
                        self.delegate?.RequestConnection(json: self.json, status: (response.response?.statusCode)!, Message: "\(self.json["Message"])")
                    })
                } else {
                    self.json = JSON(result!)
                    DispatchQueue.main.async(execute:  {
                        self.delegate?.RequestConnection(json: self.json, status: (response.response?.statusCode)!, Message: "\(self.json["Message"])")
                    })
                }
                break;
            case .failure(let error):
                print(error)
                break;
            }
        }
    }
}

为什么协议会执行该功能以显示警报。

有一些方法,只要协议执行,它就可以执行一些功能

1 个答案:

答案 0 :(得分:1)

ViewController课程中,您符合协议RequestProtocol。这意味着您可以成为API的代表。您创建了一个名为receiverDelegateViewController的实例,但此实例尚未加载。你应该改变:

senderDelegateRequest.delegate = receiverDelegateRequestRegistro

senderDelegateRequest.delegate = self

API中的代表应致电RequestConnection,而不是ViewController