声明枚举路由器 Alamofire swift 3.0
Posted
技术标签:
【中文标题】声明枚举路由器 Alamofire swift 3.0【英文标题】:Declare enum Router Alamofire swift 3.0 【发布时间】:2016-09-25 13:24:53 【问题描述】:我目前正在使用 cocoapods 1.1.0.rc.2。我已经安装了 Alamofire 吊舱。对于 1.1.0.rc.2 版本,它应该适用于 swift 3.0。 但是我正在尝试声明以下枚举
enum Router: URLRequestConvertible
static let baseURLString = "https://api.instagram.com"
static let clientID = "myID"
static let redirectURI = "http://www.example.com/"
static let clientSecret = "mySecret"
case PopularPhotos(String, String)
case requestOauthCode
static func requestAccessTokenURLStringAndParms(code: String) -> (URLString: String, Params: [String: AnyObject])
let params = ["client_id": Router.clientID, "client_secret": Router.clientSecret, "grant_type": "authorization_code", "redirect_uri": Router.redirectURI, "code": code]
let pathString = "/oauth/access_token"
let urlString = Instagram.Router.baseURLString + pathString
return (urlString, params as [String : AnyObject])
// MARK: URLRequestConvertible
var URLRequest: NSMutableURLRequest
let result: (path: String, parameters: [String: AnyObject]?) =
switch self
case .PopularPhotos (let userID, let accessToken):
let params = ["access_token": accessToken]
let pathString = "/v1/users/" + userID + "/media/recent"
return (pathString, params as [String : AnyObject]?)
case .requestOauthCode:
let pathString = "/oauth/authorize/?client_id=" + Router.clientID + "&redirect_uri=" + Router.redirectURI + "&response_type=code"
return (pathString, nil)
()
let baseURL = NSURL(string: Router.baseURLString)!
let URLRequest = NSURLRequest(url: NSURL(string: result.path ,relativeTo:baseURL as URL)! as URL)
let encoding = Alamofire.ParameterEncoding.encode(baseURL as! ParameterEncoding)
//let encoding = Alamofire.ParameterEncoding.URL
return encoding.encode(URLRequest, parameters: result.parameters).0
但是在构建这个时我得到了以下错误。
Type 'Router' does not conform to protocol 'URLRequestConvertible'
有人知道我在这里缺少什么吗?
【问题讨论】:
我遇到了同样的问题。你有没有找到任何解决方案。谢谢 @ravisendhav 不,不幸的是我还没有找到任何东西 您可以在我下面的帖子中查看解决方案。 【参考方案1】:enum Router: URLRequestConvertible
static let baseURLString = "www.google.com"
case getToken([String: AnyObject])
var method: HTTPMethod
switch self
case .getToken:
return .post
default:
break
var path: String
switch self
case .getToken:
return "token"
default:
break
func asURLRequest() throws -> URLRequest
let url = Foundation.URL(string: baseURLString)!
var urlRequest = URLRequest(url: url.appendingPathComponent(path))
urlRequest.httpMethod = method.rawValue
urlRequest.setValue("application/json", forHTTPHeaderField: "Content")
urlRequest.setValue("keep-alive", forHTTPHeaderField: "Connection")
switch self
case .getToken(let parameters):
urlRequest = try URLEncoding.default.encode(urlRequest, with: parameters)
default:
break
return urlRequest
【讨论】:
以上是关于声明枚举路由器 Alamofire swift 3.0的主要内容,如果未能解决你的问题,请参考以下文章
带参数的 Alamofire 4 Swift 3 GET 请求
带有 Swift 3 的 Alamofire 4.3,POST 请求不适用于 URL 参数
移动到 cocoapod 时,Swift Routing 枚举崩溃
响应和响应序列化程序 Swift 3.0 的 Alamofire 3->4 问题