how to send a string in body with rawdata in swift 4 without alamofire?

709 Views Asked by At
      {
        "1":[{"name":"some product","type":"simple","quantity":"2","price":"500"}],
        "2":[{"name":"Seller 2 add no 2","type":"feature","quantity":"1","price":"500"}],
        "is_free_quota":"0",
        "quotationIsVerified":"0"

      }

this is the string which I have to send

1

There are 1 best solutions below

0
Hassan Seham On

//in this function we are sending token for authentication and data is sending in the raw data form body... with out parameteres and without alamofire

func postRequest() -> Void) {

    let parameters = [""]

    let url = URL(string: "http://192.168.10.7/retbajri/public/api/request/quot")!
    print(url)
    let user1 = ["name_or any string data which you want to post"]
    let data : Data = user1.data(using: .utf8)!
    //create the session object
    let session = URLSession.shared
    //now create the Request object using the url object
    var request = URLRequest(url: url)
    request.httpMethod = "POST" //set http method as POST


    do {
        request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to data object and set it as request body
    } catch let error {
        print(error.localizedDescription)
        completion(nil, error)
    }

    //HTTP Headers
    request.setValue("Bearer \(ttkknn)", forHTTPHeaderField: "Authorization")
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")
    request.setValue(NSLocalizedString("lang", comment: ""), forHTTPHeaderField:"Accept-Language");

    request.httpBody = data
    //create dataTask using the session object to send data to the server
    let task = session.dataTask(with: request, completionHandler: { data, response, error in

        guard error == nil else {
            completion(nil, error)
            return
        }


        guard let data = data else {
            completion(nil, NSError(domain: "dataNilError", code: -100001, userInfo: nil))
            return
        }

        do {
            //create json object from data
            guard let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] else {
                completion(nil, NSError(domain: "invalidJSONTypeError", code: -100009, userInfo: nil))
                return
            }
            print(json)

        } catch let error {
            print(error.localizedDescription)
            completion(nil, error)
        }
    })
    task.resume()
}