Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
140 views
in Technique[技术] by (71.8m points)

json - Unable to add parameter to API in swift

I am getting parameter value from other viewcontroller, and i am getting parameter valueperfectly but which i am unable to add to API

here if i hardcode eventStatus then its working

and eventStatus value from otherviewcontroller also coming perfectly which i am unable to add to API

if i hard code like this its working

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

Code: here i am getting correct eventStatus value but while breakpoint its control goes to else, why?

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()
        }
}
}
}

where i am wrong, why eventStatus value not adding to API.. please suggest me

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

it looks like you have a POST request and you need to use request data instead URL parameters.

HTTP Request in Swift with POST method here you can see:

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

You also need to create parameters with eventStatus. And put it in

request.httpBody = parameters.percentEncoded()

If this endpoint on your server waits on this data in request body than you could not add it like a URL parameter.

Also, don't forget these 2 extensions from the example

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
    }()
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...