Заголовки HTTP с NSURLRequest в swift
У кого-нибудь есть идея, как настроить HTTP-заголовки с NSURLRequest в Swift? У меня настроена аутентификация на моем сервере, и ему нужен только токен, переданный ему, но у меня возникли проблемы с настройкой заголовка
мой код:
func getLatestData() {
var loggedInUsersNumber:String = SharingManager.sharedInstance.userID
var usersDataPoint:String = StormDataPoint + loggedInUsersNumber
activityIND.hidden = false
activityIND.startAnimating()
let request = NSURLRequest(URL: NSURL(string: usersDataPoint)!)
let tokenString = SharingManager.sharedInstance.authToken
//request.setValue("Token " + tokenString, forKey: "Authorization")
let urlSession = NSURLSession.sharedSession()
let task = urlSession.dataTaskWithRequest(request, completionHandler: {
(data, response, error) -> Void in
if let error = error {
print(error)
return }
Я создал свойство "tokenString", чтобы быть токеном для передачи в заголовок и в следующей строке, где я прокомментировал его. запрос.setvalue-я вставил его и получил сообщение об ошибке "невозможно переопределить тип данных". Все мои поиск показывает Objective C help. Есть ли лучший способ попытаться передать заголовок?
4 ответов
в Swift 3 Используйте URLRequest
структура вместо NSURLRequest
(аналогично, NSURL
↦ URL
, NSURLSession
↦ URLSession
, etc.).
затем использовать addValue(_:forHTTPHeaderField:)
добавить заголовок.
// swift 3:
var request = URLRequest(url: URL(string: usersDataPoint)!)
request.addValue("Token \(tokenString)", forHTTPHeaderField: "Authorization")
в Swift 2.2, вы используете NSMutableURLRequest
если вам нужно, чтобы изменить его.
// swift 2:
let request = NSMutableURLRequest(URL: NSURL(string: usersDataPoint)!)
request.addValue("Token \(tokenString)", forHTTPHeaderField: "Authorization")
вы можете создать изменяемый запрос URL, а затем установить значение для имени Поля.
let request = NSMutableURLRequest(URL: NSURL(string: yourURLString)!)
request.setValue("\(yourValue)", forHTTPHeaderField: "Header-field-name")
Swift3 больший пример
var req: URLRequest = /* create requets */
req.setValue("Bearer Y3GzLG2x6wSXihmUGhwGFw", forHTTPHeaderField: "Authorization")
req.timeoutInterval = 10
let task = URLSession.shared.dataTask(with: req, completionHandler: { (data, response, error) in
print("completionHandler invoked")
})
task.resume()
private func getHeaderData(url:String) -> Dictionary<String, String> {
let strLanguage:String = LanguageManager.sharedInstance.getCurrentLanuage()
let params:[String:String] = [WSKeys.XAPIkey: XAPIKeyString,
WSKeys.language:strLanguage
]
return params
}
class NetworkManager: NSObject {
static let shared = NetworkManager()
//MARK: - WS CALLS Methods
func GETRequset(showLoader: Bool, url:String, success:@escaping (AnyObject!) -> Void, failed:@escaping (AnyObject!) -> Void) {
self.startProgressLoading(isStart: showLoader)
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "GET"
request.allHTTPHeaderFields = getHeaderData(url: url)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("O/P error=\(error.debugDescription)")
self.stopProgressLoading()
failed(error.debugDescription as AnyObject!)
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
self.stopProgressLoading()
failed(response as AnyObject!)
}
let responseString = String(data: data, encoding: .utf8)
self.stopProgressLoading()
DispatchQueue.main.async {
success(responseString as AnyObject!)
}
}
task.resume()
}
func POSTRequset(showLoader: Bool, url:String, parameter:[String : AnyObject]?, success:@escaping (AnyObject!) -> Void, failed:@escaping (AnyObject!) -> Void) {
self.startProgressLoading(isStart: showLoader)
let boundary = "Boundary-\(NSUUID().uuidString)"
let url = URL(string: url)
let request = NSMutableURLRequest(url: url!)
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
let headerData = getHeaderData(url: (url?.absoluteString)!)
request.allHTTPHeaderFields = headerData
var body = Data()
if parameter != nil {
for (key, value) in parameter! {
body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n".data(using: String.Encoding.utf8)!)
body.append("\(value)\r\n".data(using: String.Encoding.utf8)!)
}
}
body.append("--\(boundary)--\r\n".data(using: String.Encoding.utf8)!)
request.httpBody = body
let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: {
data, response, error in
print("##############################################################################")
guard let data = data, error == nil else {
failed(error.debugDescription as AnyObject!)
self.stopProgressLoading()
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
self.stopProgressLoading()
failed(response as AnyObject!)
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode == 401 {
self.stopProgressLoading()
failed(response as AnyObject!)
}
let responseString = String(data: data, encoding: .utf8)
let dict = self.convertToDictionary(text: responseString!)
if dict != nil
{
print("O/P responseDict = \(String(describing: dict))")
}
else
{
print("O/P responseString = \(String(describing: responseString))")
}
print("##############################################################################")
if (dict?["status"]) != nil {
let strStatus = dict?[WSKeys.status] as! NSNumber
let strMessage = dict?[WSKeys.message] as! NSString
self.stopProgressLoading()
if strStatus == 401{
failed(strMessage)
DispatchQueue.main.async {
getDelegate().logOut()
}
} else {
DispatchQueue.main.async {
success(dict as AnyObject!)
}
}
}
})
task.resume()
}
func POSTJsonArrayRequset(showLoader: Bool, url:String, parameter:[String : AnyObject]?, success:@escaping (AnyObject!) -> Void, failed:@escaping (AnyObject!) -> Void) {
self.startProgressLoading(isStart: showLoader)
let request = NSMutableURLRequest(url: URL(string:url)!)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try! JSONSerialization.data(withJSONObject: parameter)
request.httpMethod = "POST"
let headerData = getHeaderData(url: url)
request.allHTTPHeaderFields = headerData
let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: {
data, response, error in
print("##############################################################################")
print("URL: \(String(describing: url))")
print("PARAMS: \(String(describing: parameter))")
print("Headers: \(headerData)")
print("Method: Post")
guard let data = data, error == nil else {
print("O/P error=\(error.debugDescription)")
failed(error.debugDescription as AnyObject!)
self.stopProgressLoading()
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
print("O/P statusCode should be 200, but is \(httpStatus.statusCode)")
// print("O/P response = \(String(describing: response))")
self.stopProgressLoading()
failed(response as AnyObject!)
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode == 401 {
print("O/P statusCode should be 401, but is \(httpStatus.statusCode)")
// print("O/P response = \(String(describing: response))")
self.stopProgressLoading()
failed(response as AnyObject!)
}
let responseString = String(data: data, encoding: .utf8)
let dict = self.convertToDictionary(text: responseString!)
if dict != nil
{
print("O/P responseDict = \(String(describing: dict))")
}
else
{
print("O/P responseString = \(String(describing: responseString))")
}
print("##############################################################################")
let strStatus = dict?[WSKeys.status] as! NSNumber
let strMessage = dict?[WSKeys.message] as! NSString
self.stopProgressLoading()
if strStatus == 401{
failed(strMessage)
DispatchQueue.main.async {
getDelegate().logOut()
}
} else {
DispatchQueue.main.async {
success(dict as AnyObject!)
}
}
})
task.resume()
}
func POSTJsonArrayRequsetTap(showLoader: Bool, url:String, parameter:[String : AnyObject]?, success:@escaping (AnyObject!) -> Void, failed:@escaping (AnyObject!) -> Void) {
self.startProgressLoading(isStart: showLoader)
let request = NSMutableURLRequest(url: URL(string:url)!)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try! JSONSerialization.data(withJSONObject: parameter)
request.httpMethod = "POST"
let headerData = ["content-type": "application/json"]
request.allHTTPHeaderFields = headerData
let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: {
data, response, error in
print("##############################################################################")
print("URL: \(String(describing: url))")
print("PARAMS: \(String(describing: parameter))")
print("Headers: \(headerData)")
print("Method: Post")
guard let data = data, error == nil else {
print("O/P error=\(error.debugDescription)")
failed(error.debugDescription as AnyObject!)
self.stopProgressLoading()
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
print("O/P statusCode should be 200, but is \(httpStatus.statusCode)")
// print("O/P response = \(String(describing: response))")
self.stopProgressLoading()
failed(response as AnyObject!)
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode == 401 {
print("O/P statusCode should be 401, but is \(httpStatus.statusCode)")
// print("O/P response = \(String(describing: response))")
self.stopProgressLoading()
failed(response as AnyObject!)
}
let responseString = String(data: data, encoding: .utf8)
let dict = self.convertToDictionary(text: responseString!)
if dict != nil
{
print("O/P responseDict = \(String(describing: dict))")
}
else
{
print("O/P responseString = \(String(describing: responseString))")
}
print("##############################################################################")
let strStatus = dict?[WSKeys.status] as! NSNumber
let strMessage = dict?[WSKeys.message] as! NSString
self.stopProgressLoading()
if strStatus == 401{
failed(strMessage)
DispatchQueue.main.async {
getDelegate().logOut()
}
} else {
DispatchQueue.main.async {
success(dict as AnyObject!)
}
}
})
task.resume()
}
func convertToDictionary(text: String) -> [String: Any]? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print(error.localizedDescription)
}
}
return nil
}
func MultipartFormDataRequset(showLoader: Bool, urlString:String, mediaKey:String?, mediaDataArray:[Dictionary<String, AnyObject>]?, parameter:[String : AnyObject]?, success:@escaping (AnyObject!) -> Void, failed:@escaping (AnyObject!) -> Void) {
let boundary = "Boundary-\(NSUUID().uuidString)"
let url = URL(string: urlString)
let request = NSMutableURLRequest(url: url!)
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
request.allHTTPHeaderFields = getHeaderData(url: urlString)
var body = Data()
if parameter != nil {
for (key, value) in parameter! {
body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n".data(using: String.Encoding.utf8)!)
body.append("\(value)\r\n".data(using: String.Encoding.utf8)!)
}
}
if mediaDataArray != nil {
var i = 0
for var dict in mediaDataArray! {
let data = dict["data"]
let mimetype = "application/octet-stream"
body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
let key = "\(String(describing: mediaKey))[\(i)]"
body.append("Content-Disposition: form-data; name=\"\(key)\"; filename=\"\(dict["fileName"]!)\"\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Type: \(mimetype)\r\n\r\n".data(using: String.Encoding.utf8)!)
body.append(data! as! Data)
body.append("\r\n".data(using: String.Encoding.utf8)!)
i = i + 1
}
}
body.append("--\(boundary)--\r\n".data(using: String.Encoding.utf8)!)
request.httpBody = body
let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: {
data, response, error in
guard let data = data, error == nil else {
print("O/P error=\(error.debugDescription)")
failed(error.debugDescription as AnyObject!)
self.stopProgressLoading()
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
print("O/P statusCode should be 200, but is \(httpStatus.statusCode)")
print("O/P response = \(String(describing: response))")
self.stopProgressLoading()
failed(response as AnyObject!)
}
let responseString = String(data: data, encoding: .utf8)
print("O/P responseString = \(String(describing: responseString))")
self.stopProgressLoading()
DispatchQueue.main.async {
success(responseString as AnyObject!)
}
})
task.resume()
}
func MultipartFormDataForSingleMediaRequset(showLoader: Bool, url:String, mediaData:Data?, mediaKey:String?, parameter:[String : AnyObject]?, success:@escaping (AnyObject!) -> Void, failed:@escaping (AnyObject!) -> Void) {
let startBoundry:String = "AaB03x"
let url = URL(string: url)!
var request:URLRequest = URLRequest(url: url as URL, cachePolicy: URLRequest.CachePolicy.reloadIgnoringLocalCacheData, timeoutInterval: 10)
request.allHTTPHeaderFields = getHeaderData(url: url.absoluteString)
let boundary:String = "--\(startBoundry)"
let endMPboundary:String = "\(boundary)--"
let imageData:Data = mediaData!
var body:String = String()
if parameter != nil {
for (key, value) in parameter! {
body = body + "\(boundary)\r\n"
body = body + "Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n"
body = body + "\(value)\r\n"
}
}
body = body + "\(boundary)\r\n"
body = body + "Content-Disposition: form-data; name=\"\(mediaKey!)\"; filename=\"\("attachment.png")\"\r\n"
body = body + "Content-Type: image/png\r\n\r\n"
let end:String = "\r\n\(endMPboundary)"
var myRequestData:Data = Data();
myRequestData.append(body.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))!)
myRequestData.append(imageData as Data)
myRequestData.append(end.data(using: String.Encoding.utf8)!)
let content:String = "multipart/form-data; boundary=\(startBoundry)"
request.setValue(content, forHTTPHeaderField: "Content-Type")
request.setValue("\(myRequestData.count)", forHTTPHeaderField: "Content-Length")
request.httpBody = myRequestData as Data
request.httpMethod = "POST"
let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: {
data, response, error in
guard let data = data, error == nil else {
print("O/P error=\(error.debugDescription)")
failed(error.debugDescription as AnyObject!)
self.stopProgressLoading()
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
print("O/P statusCode should be 200, but is \(httpStatus.statusCode)")
print("O/P response = \(String(describing: response))")
self.stopProgressLoading()
failed(response as AnyObject!)
}
let responseString = String(data: data, encoding: .utf8)
print("O/P responseString = \(String(describing: responseString))")
self.stopProgressLoading()
DispatchQueue.main.async {
success(responseString as AnyObject!)
}
})
task.resume()
}
private func startProgressLoading(isStart: Bool) {
DispatchQueue.main.async {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
}
}
private func stopProgressLoading() {
DispatchQueue.main.async {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
}
}
func getProductDetail(productID:String, success: @escaping (ProductDetailDataModel?) -> Void, failed: @escaping (AnyObject!) -> Void) {
if isConnectedToInternet() {
theController.showLoader()
let addressURL = productDetailURL
let theParamDict = [WSKeys.product_id : productID] as [String: AnyObject]
NetworkManager.shared.POSTRequset(showLoader: true, url: addressURL, parameter: theParamDict , success: { (responseObject) in
self.theController.hideLoader()
guard let data = responseObject.object(forKey: "data") as? NSDictionary else {
success(nil)
return
}
guard let storeInfo = data.object(forKey: "productDetailsInfo") as? [String: AnyObject] else {
success(nil)
return
}
let dataArray = self.setStoreDetail(dictData: storeInfo)
success(dataArray)
}, failed: { (error) in
self.theController.hideLoader()
print("error is \(error)")
failed(error)
})
} else {
failed("No Internet Connection" as AnyObject)
}
}
struct ProductDetailDataModel {
var strStoreID: String? = nil
var strPrice:NSNumber? = nil
var strType:NSNumber? = nil
var strSellerID:String? = nil
var dicSeller:[String:AnyObject] = [:]
var arrStoreMedia: [[String: AnyObject]]?
mutating func setTheProperties(theDict: [String: AnyObject]) {
strStoreID = "\(String(describing: theDict["product_id"]!))"
strPrice = theDict["price"] as? NSNumber
dicSeller = theDict["seller"] as! [String:AnyObject]
arrStoreMedia = theDict["products_medias"] as? [[String: AnyObject]]
for product in arrStoreMedia!
{
if let photo_original = product["photo_original"] as? String, photo_original != ""
{
strPhotoOrignal = photo_original
break;
}
}
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let cell = tblHome.dequeueReusableCell(withIdentifier: "CellHeadetTC") as! CellHeadetTC
cell.advertisements = homeDetail.arrAdvertisement
return cell
}
else if indexPath.row == 1 {
let cell = tblHome.dequeueReusableCell(withIdentifier: "CellHomeTableView") as! CellHomeTableView
cell.selectionStyle = .none
cell.nav = self.navigationController
cell.arrCat = homeDetail.arrCategory
cell.collectionViewCategory.reloadData()
return cell
}
else {
let cell = tblHome.dequeueReusableCell(withIdentifier: "CellServiceTableView") as! CellServiceTableView
cell.selectionStyle = .none
if indexPath.row == 2 {
cell.lblheader.text = "Pending Service".localized()
cell.arrService = homeDetail.arrRecentService
cell.btnSeeAll.addTarget(self, action: #selector(HomeViewControlller.btnRecentSeeAllClicked(_:)), for: .touchUpInside)
}
else{
cell.lblheader.text = "Upcoming Services".localized()
cell.arrService = homeDetail.arrUpcommingService
cell.btnSeeAll.addTarget(self, action : #selector(HomeViewControlller.btnUpcomingSeeAllClicked(_:)), for: .touchUpInside)
}
return cell
}
}
var arrCategory = [Categorys]()
let temp = responseDict["data"]!.dictionaryValue
let arrCategory = temp["categories"]!.arrayValue
let homeClass = HomeClass()
for i in 0..<arrCategory.count {
let dict = arrCategory[i].dictionaryValue
let categoryData = Categorys()
categoryData.strId = dict["id"]?.stringValue
homeClass.arrCategory.append(categoryData)
}