Alamofire/Swiftyjson - Pass JSON type to Objc protocol delegate

时间:2016-04-12 00:54:54

标签: ios json swift swifty-json

With the code below, I'm able to launch an HTTP request to my server and retrieve a JSON object thanks to Alamofire and Swiftyjson.

But I'm not able to pass the custom class JSON from Swiftyjson as an argument of my delegate method.

What should I do to fix this error?

Code line with error:

optional func didReceiveUserInfo(userInfo: JSON) //This the line I get the error

Error: Method cannot be a member of an @objc protocol because the type of parameter cannot be represented in in Objective-C

Here is the full code I'm using:

import UIKit
import Alamofire
import SwiftyJSON

@objc protocol UserModelDelegate {
    optional func didReceiveUserInfo(userInfo: JSON) //This is the line I get the error
}

class UserModel: NSObject, NSURLSessionDelegate {

    // Instantiate the delegate
    var delegate: UserModelDelegate?

    override init() {
        super.init()
    }

    func getUserInfo(token: String) {

        let url = "http://test.app/api/userInfo"

        let headers = [
            "Authorization":"Bearer \(token)",
            "Content-Type": "application/x-www-form-urlencoded"
        ]

        Alamofire.request(.GET, url, headers: headers).responseJSON { response in

            switch response.result {

                case .Success(let data):
                    let json = JSON(data)
                    self.delegate?.didReceiveUserInfo?(json) //This is where I pass the JSON custom class type as an argument

                case .Failure(let error):
                print("Request failed with error: \(error)")
            }
        }
    }
}

2 个答案:

答案 0 :(得分:0)

我可能会使协议要求不是可选的,在这种情况下,由于您的委托只有一个要求,因此完全有意义。您遇到的问题是因为您需要JSON对象类型与Objective-C兼容。您可以通过使类继承自Objective-C类(如NSObject)来实现。 您应该做的另一件事是在delegate UserModel中声明weak属性,以避免保留周期。

编辑:如何使swift类与Objective-C兼容的示例:

class JSON: NSObject {
//the code
}

注意:我之前曾声明您需要在类中添加@objc属性。除非您想在Objective-C中使用其他名称显示您的类,否则实际上没有必要。

有关Swift和Objective-C互操作性的更多信息read here

答案 1 :(得分:0)

以下代码正在运行:

pub serve