ios - 协议(protocol)不会在 swift Ios 中调用

标签 ios swift

您好,我正在使用 NSUrlSession 在我的 Swift 编程中调用 Web 服务,而且我是 Swift 编程语言的新手。

在我下面的程序中,我使用 BackGroundClass 来集成网络服务,在获得结果后,我使用协议(protocol)在我的 ViewController 中接收该响应,但这些协议(protocol)功能不是调用我的 ViewController 可以有人帮助我吗。

View Controller :-

import UIKit

class ViewController: UIViewController,sampleProtocal {

    override func viewDidLoad() {
        super.viewDidLoad()

        BackGroundClass.delegate = self

        let params = ["scancode":"KK03799-008", "UserName":"admin"] as Dictionary<String, String>
        let backGround=BackGroundClass();
        backGround.callPostService("my Url", parameters: params)

    }

    func getResponse(result: NSDictionary) {
        print("Final response is\(result)");
    }

    func getErrorResponse(error: NSString) {
        print("Final Eroor code is\(error)")
    }
}

背景类:-

import UIKit

protocol sampleProtocal :  NSObjectProtocol{

    func getResponse(result:NSDictionary)
    func getErrorResponse(error:NSString)
}

class BackGroundClass: NSObject {

   var delegate:sampleProtocal?

    func callPostService(url:String,parameters:NSDictionary){


        print("url is===>\(url)")

        let request = NSMutableURLRequest(URL: NSURL(string:url)!)

        let session = NSURLSession.sharedSession()
        request.HTTPMethod = "POST"

        //Note : Add the corresponding "Content-Type" and "Accept" header. In this example I had used the application/json.
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(parameters, options: [])

        let task = session.dataTaskWithRequest(request) { data, response, error in
            guard data != nil else {
                print("no data found: \(error)")
                return
            }

            do {
                if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
                    print("Response: \(json)")
                    self.mainResponse(json)
                } else {
                    let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)// No error thrown, but not NSDictionary
                    print("Error could not parse JSON: \(jsonStr)")
                    self.eroorResponse(jsonStr!)
                }
            } catch let parseError {
                print(parseError)// Log the error thrown by `JSONObjectWithData`
                let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
                print("Error could not parse JSON: '\(jsonStr)'")
                self.eroorResponse(jsonStr!)
            }
        }

        task.resume()
    }

    func mainResponse(result:NSDictionary){
        delegate?.getResponse(result)
    }

    func eroorResponse(result:NSString){
        delegate?.getErrorResponse(result)
    }
}

最佳答案

因为你没有分配委托(delegate)

// remove this
//BackGroundClass.delegate = self

let params = ["scancode":"KK03799-008", "UserName":"admin"] as Dictionary<String, String>
let backGround=BackGroundClass();
// assign delegate here
backGround.delegate = self
backGround.callPostService("my Url", parameters: params)

关于ios - 协议(protocol)不会在 swift Ios 中调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44918182/

相关文章:

iphone - 当出现问题时,我应该如何通知自己(开发人员)?

ios - 原型(prototype) Collection View 单元格 "Unable to simultaneously satisfy constraints."警告

swift - 准备(对于 : sender:) not getting called during segue from button to tab bar controller (in Swift 4, Xcode 9)

ios - 使用参数编码 JSONEncoding.default 时请求超时

ios - 如何在 SWIFT 中设置捏合手势识别器的最小值和最大值?

ios - 从 ios 应用程序登录 linkedin

ios - 从 Swift 中的另一个类访问 ViewController 类

ios - 选择文本字段时使 UITableView 滚动

ios - 如何将 ImageView 及其属性从一个 View Controller 传递到另一个 View Controller ?

objective-c - 从 'struct myStruct *' 分配给 'struct myStruct *' 的不兼容指针类型