无法快速向API添加参数

时间:2020-08-16 16:58:14

标签: json swift

我正在从其他ViewController获取参数值,并且已经在完美获取参数值,但是无法将其添加到API

在这里,如果我对eventStatus进行硬编码,则它可以正常工作

来自其他viewcontroller的

eventStatus值也很合适,我无法将其添加到API

如果我像这样硬编码就可以了

var eventType = "Draft"
let string = Constants.GLOBAL_URL + "/get/allevents/?eventstatus=\(self.eventType)"

代码:在这里,我得到了正确的eventStatus值,但是在断点处它的控制权移到了其他地方,为什么?

class EventsViewController: UIViewController {

var eventsListArray = [AnyObject]()
// var eventType = "Draft"
var eventType: String!

var eventList : EventsModel? = nil

@IBOutlet weak var eventsTableView: UITableView!


override func viewDidLoad() {
    super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    getAllEventsList()
}

func getAllEventsList() {
    DispatchQueue.main.async {
    let headers = ["deviceid": deviceId,"userType": "personal","key": personalId]
    DispatchQueue.main.async {
        //let string = Constants.GLOBAL_URL + "/get/allevents/?eventstatus=\(self.eventType)"
    let string = Constants.GLOBAL_URL + "/get/allevents"
    var urlComponents = URLComponents(string: string)

    let eventStatus = self.eventType
        
        print("event status value in API call \(eventStatus)")
    let requestEventType = URLQueryItem(name: "eventstatus", value: eventStatus)

    urlComponents?.queryItems = [requestEventType]
    let urlStr = urlComponents?.url
    
    var request = URLRequest(url: urlStr!, 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
        DispatchQueue.main.async {

        if error == nil {

            let httpResponse = response as? HTTPURLResponse
            if httpResponse!.statusCode == 200 {
                do {
                    let jsonObject  = try JSONSerialization.jsonObject(with: data!) as! [String :Any]
                    print("publish event \(jsonObject)")
                    
                    self.eventList = EventsModel.init(fromDictionary: jsonObject)
                    
                    DispatchQueue.main.async {

                    if self.eventList?.events.count != 0 {
                        DispatchQueue.main.async {
                            self.eventsTableView.reloadData()
                        }
                    }
                    
                    else {
                        
                        DispatchQueue.main.async {
                            Constants.showAlertView(alertViewTitle: "", Message: "No Events \(self.eventType)", on: self)
                            self.eventList?.events.removeAll()
                            self.eventsTableView.reloadData()
                        }
                    }
                }
                } catch { print(error.localizedDescription) }
            } else {
                Constants.showAlertView(alertViewTitle: "", Message: "Something went wrong, Please try again", on: self)
            }
    }
    }
    })
        
    dataTask.resume()
        }
}
}
}

我错了,为什么eventStatus的值没有添加到API中。请建议我

2 个答案:

答案 0 :(得分:0)

看起来您有POST请求,需要使用请求数据代替URL参数。

HTTP Request in Swift with POST method在这里您可以看到:

let parameters: [String: Any] = [
    "eventstatus": yourValue
]
request.httpBody = parameters.percentEncoded()

您还需要使用 eventStatus 创建参数。并放入

request.httpBody = parameters.percentEncoded()

如果服务器上的此端点在请求正文中等待该数据,则无法像URL参数一样添加它。

此外,请不要忘记示例中的这两个扩展

extension Dictionary {
    func percentEncoded() -> Data? {
        return map { key, value in
            let escapedKey = "\(key)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? ""
            let escapedValue = "\(value)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? ""
            return escapedKey + "=" + escapedValue
        }
        .joined(separator: "&")
        .data(using: .utf8)
    }
}

extension CharacterSet { 
    static let urlQueryValueAllowed: CharacterSet = {
        let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
        let subDelimitersToEncode = "!$&'()*+,;="

        var allowed = CharacterSet.urlQueryAllowed
        allowed.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
        return allowed
    }()
}

答案 1 :(得分:0)

从评论中的讨论中,解决方案必须显而易见。尽管您似乎对此有些疑惑,但我添加此内容可以帮助您。 eventType的值永远不会分配给某个值,除非您在API调用之前的代码中的某个点设置了它的值,否则它将保留为nil。因此,您可以通过以下方式解决此问题:

let string = "https://www.google.com" + "/get/allevents"
var urlComponents = URLComponents(string: string)

let eventStatus = self.eventType ?? "Published" // here value is defaulted to "Published"
let requestEventType = URLQueryItem(name: "eventstatus", value: eventStatus)

urlComponents?.queryItems = [requestEventType]
let urlStr = urlComponents?.url
print(urlStr?.absoluteString)

在这里,我们为eventTypeeventType的情况设置nil的默认值。