我正在尝试将我的代码从swift 2版本迁移到swift 3版本。 我无法迁移以下代码部分,我没有找到任何解决方案。 我该怎么办?
// MARK:URLRequestConvertible
public var URLRequest: NSMutableURLRequest {
let urlComponent = NSURLComponents(string: Router.baseURL)!
urlComponent.path = Router.basePath.stringByAppendingString(path)
let mutableURLRequest = NSMutableURLRequest(URL: urlComponent.URL!)
mutableURLRequest.HTTPMethod = method.rawValue
var parameters: [String: AnyObject] = Dictionary()
parameters["key"] = Router.key
parameters["hl"] = "en"
switch self {
case .getMostPopularVideos(let pageToken):
parameters["part"] = "snippet,contentDetails,statistics"
parameters["chart"] = "mostPopular"
parameters["videoCategoryId"] = TubeTrends.Settings.topTrendsCat
if let pageToken = pageToken {
parameters["pageToken"] = pageToken
}
return Alamofire.ParameterEncoding.URL.encode(mutableURLRequest, parameters: parameters).0 //This part Giving Error like Alamofire Type 'ParameterEncoding' has no member 'URL'
// default:
// return mutableURLRequest
}
}
}
答案 0 :(得分:6)
在Swift 3中看起来有很多变化。尝试通过参考以下代码来更改代码。
func asURLRequest() throws -> URLRequest {
let url = URL(string: Router.baseURLString)!
var urlRequest = URLRequest(url: url.appendingPathComponent(path))
urlRequest.httpMethod = method.rawValue
if let token = Router.OAuthToken {
urlRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
}
switch self {
case .createUser(let parameters):
return try Alamofire.JSONEncoding.default.encode(urlRequest, with: parameters)
case .updateUser(_, let parameters):
return try Alamofire.URLEncoding.default.encode(urlRequest, with: parameters)
default:
return urlRequest
}
}
答案 1 :(得分:1)
我会将此计算属性的名称更改为request
,以避免与新类型名称URLRequest
发生冲突。巧合的是,此计算属性应使用URLRequest
:
public var request: URLRequest {
let url = URL(string: Router.baseURL)!
.appendingPathComponent(Router.basePath)
.appendingPathComponent(path)
var request = URLRequest(url: url)
request.httpMethod = method.rawValue
var parameters = [String: Any]()
parameters["key"] = Router.key
parameters["hl"] = "en"
switch self {
case .getMostPopularVideos(let pageToken):
parameters["part"] = "snippet,contentDetails,statistics"
parameters["chart"] = "mostPopular"
parameters["videoCategoryId"] = TubeTrends.Settings.topTrendsCat
if let pageToken = pageToken {
parameters["pageToken"] = pageToken
}
return try! Alamofire.URLEncoding.default.encode(request, with: parameters)
}
}