我想在URL体中添加如下参数。
func getUserProfile() {
let deviceId: String = "HardcodeDEVICEIDforiTaag"//(UIDevice.current.identifierForVendor?.uuidString)!
let personalId: String = UserDefaults.standard.string(forKey: "USERID") ?? ""
let headers = ["deviceid": deviceId,"userType": "personal","key": personalId]
let string = "http://itaag-env-1.ap-south-1.elasticbeanstalk.com/getprofile/"
var urlComponents = URLComponents(string: string)
let requestedUserType = URLQueryItem(name: "requestedUserType", value: "personal")
let requestedItem = URLQueryItem(name: "requestedKey", value: personalId)
urlComponents?.queryItems = [requestedItem, requestedUserType]
let urlStr = urlComponents?.url
print(urlStr?.absoluteString)
let request = NSMutableURLRequest(url: NSURL(string:urlStr)! as URL,cachePolicy: .useProtocolCachePolicy,timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers as! [String : String]
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if error == nil {
let httpResponse = response as? HTTPURLResponse
if httpResponse!.statusCode == 200 {
do {
let jsonObject = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! [String :AnyObject]
self.userModel = ProfileModel.init(fromDictionary: jsonObject)
print("profile json \(jsonObject)")
print("profile personalid 2222\(personalId)")
if (self.userModel?.userId) != nil {
DispatchQueue.main.async {
self.updateUserDetails()
self.addressTableview.reloadData()
}
} else { DispatchQueue.main.async { Constants.showAlertView(alertViewTitle: "", Message: "No user data found", on: self)}}
} catch { print(error.localizedDescription) }
} else {
//Constants.showAlertView(alertViewTitle: "", Message: "Something went wrong, Please try again", on: self)
}
}
})
dataTask.resume()
}
然后得到错误信息。
无法将类型'URL'的值转换为预期的参数类型'String'
当我试图添加网址到请求时,我得到了上述错误。
请帮我解决这个错误。
这就是应该如何用不同的组件创建一个url。
let string = "http://itaag-env-1-south-1.elasticbeanstalk.com/getprofile"
var urlComponents = URLComponents(string: string)
let requestedItem = URLQueryItem(name: "requestedKey", value: "yourReqKey")
let requestedUserType = URLQueryItem(name: "requestedUserType", value: "personal")
urlComponents?.queryItems = [requestedItem, requestedUserType]
let url = urlComponents?.url
print(url?.absoluteString)
编辑:最后使用这段代码来获取你的请求:-。
let request = NSMutableURLRequest(url: url!, cachePolicy: .useProtocolCachePolicy,timeoutInterval: 10.0)