【问题标题】:Type does not conform to protocol 'URLRequestConvertible' with Alamofire类型不符合 Alamofire 的协议“URLRequestConvertible”
【发布时间】:2015-09-23 12:50:00
【问题描述】:

代码如下:

enum Router: URLRequestConvertible {
    //Error: Type 'Five100px.Router' does not conform to protocol 'URLRequestConvertible'

    static let baseURLString = "https://api.500px.com/v1"
    static let consumerKey = "MY_KEY"

    case PopularPhotos(Int)
    case PhotoInfo(Int, ImageSize)
    case Comments(Int, Int)

    var URLRequest: NSURLRequest {

        let (path, parameters) : (String, [String: AnyObject]) = {

            switch self {

            case .PopularPhotos(let page):
                let params = ["consumer_key": Router.consumerKey, "page": "\(page)", "feature": "popular", "rpp": "50", "include_store": "store_download", "include_status": "votes"]
                return ("/phtos", params)

            case .PhotoInfo(let photoID, let ImageSize):
                var params = ["consumer_key": Router.consumerKey, "image_size": "\(ImageSize.rawValue)"]
                return ("/photos/\(photoID)", params)

            case .Comments(let photoID, let commentsPage):
                var params = ["consumer_key": Router.consumerKey, "comments": "1", "comments_page": "\(commentsPage)"]
                return ("/photos/\(photoID)/comments", params)
            }
        }()

        let URL = NSURL(string: Router.baseURLString)
        let URLRequest = NSURLRequest(URL: URL!.URLByAppendingPathComponent(path))
        let encoding = Alamofire.ParameterEncoding.URL

        return encoding.encode(URLRequest, parameters: parameters).0
    }
}

我导入了 Alamofire 并添加了此代码,然后出现错误。我根据 raywenderlich 教程编写了这段代码:http://www.raywenderlich.com/85080/beginning-alamofire-tutorial,它是在我使用 Swift 2 时用 Swift 1.2 编写的。

【问题讨论】:

    标签: ios swift alamofire


    【解决方案1】:

    您需要在URLRequest 属性中返回NSMutableURLRequest 而不是NSURLRequest。这将修复错误。


    更新

    在 Swift 3 和 Alamofire 4 中,您需要从新的 asURLRequest() 方法返回一个 URLRequest。有关详细信息,请参阅我们更详细的 README examples

    【讨论】:

    • 这不适用于 SWIFT3,我会像这样返回 URLRequest:func asURLRequest() throws -> URLRequest
    • 没错@PiyushSanepara,上面这个只适用于Alamofire 3。在Alamofire 4中,你需要实现asURLRequest()方法以符合URLRequestConvertible。更多信息可以找到here
    【解决方案2】:

    @cnoon 的回答适用于版本 3,但如果您使用的是 Alamofire 版本 4+,则必须实施:

    func asURLRequest() throws -> URLRequest

    【讨论】:

    • 我们需要在哪里实现它。我的枚举是在这种类型中定义的 - enum Router: URLRequestConvertible { } 我遇到了与 swift 3.0 相同的问题
    • 这正是您需要实现它的地方。在您的枚举中。这是您根据枚举中的每个案例自定义返回的 URLRequest 对象的地方。通过自定义,我的意思是设置 http 方法和标头,设置超时,编码参数等......
    • 请参阅此处 Alamofire 4.0 文档的路由请求部分:github.com/Alamofire/Alamofire#routing-requests
    猜你喜欢
    • 1970-01-01
    • 2019-11-23
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-22
    相关资源
    最近更新 更多