首页 > 解决方案 > 如何在没有 alamofire 的 swift 4 中使用 rawdata 在正文中发送字符串?

问题描述

      {
        "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"

      }

这是我必须发送的字符串

标签: swift4xcode9

解决方案


//在这个函数中,我们发送令牌进行身份验证,数据以原始数据形式发送......没有参数和没有alamofire

func postRequest() -> 无效){

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

推荐阅读