如何将base64字符串发送到POST服务-Swift

时间:2019-01-22 18:07:15

标签: swift

我在将swift 4中的base64 imagen字符串发送到post服务时遇到问题。此服务在base64中收到“ string json post”和参数。

此示例:

{
  "dato1":"prueba@mail.com",
  "dato2":1,
  "video":{
    "NomVideo":"video.mp4",
    "TipVideo":"mp4",
    "ArchVideo":"Base64"
  },
  "listaImagen":[{
    "NomImagen":"imagen1.jpg",
    "TipImagen":"jpg",
    "ArchImagen":"JKANSDJKASNDASKDNSAJKDNASJKNSA"
  },
  {
    "OrdImagen":2,
    "NomImagen":"imagen2.jpg",
    "TipImagen":"jpg",
    "ArchImagen":"base64"
  }],
  "ObjetoPrincipal":{
    "objetoDato1":"akmdklamd",
    "objetoDato2":"lakmsksamk"
  }
}

但是当我在base64中发送参数时,该服务不会返回答案,如果不在base64中发送参数,则该服务会正确响应。

我的邮政服务

    class func postJsonWithHeaderAuthorization(_ url :NSString, data :NSString, authorizationParam: String, closure: @escaping (Data?, URLResponse?, Error?) -> ()){

    let url = URL(string: url as String)

    let request = NSMutableURLRequest(url: url! )

    request.httpMethod = POST
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.setValue("application/json", forHTTPHeaderField: "Accept")
    request.setValue(authorizationParam, forHTTPHeaderField: "authorization")


    let data = data.data(using: String.Encoding.utf8.rawValue)


    let task = URLSession.shared.uploadTask(with: request as URLRequest,from: data, completionHandler: { (data,response, error ) in

        closure(data ,response, error)
        return
    })

    task.resume()
}

plist配置:

应用程序传输安全设置     允许任意载荷-是

base64参数为: k + 62cf7vQn8T8o / + tVqAnlz1NIC3JJ2qEHJpjNmlU0wJ1NaVme1ZSmtKyPNADtSP7s17Z4eGNB0wf9OsP / ota8 ........(等)

1 个答案:

答案 0 :(得分:0)

我的解决方案是调整图像大小并在生成base 64字符串之后,但是我将服务更改为Alamofire API。

但是,如果我不压缩整个链,就会给我带来麻烦。

链接转换器base64更容易:Link github base 64 converter

let imageRes = imageWithImage(image: imagenTomada, scaledToSize: CGSize(width: 100, height: 100))

    let string64 = imageRes.base64(format: .png)!

我的方法

    private func service(){

    let objetDTO = crearobjetDTO()

    var parametersImagenes: Array<Dictionary<String, AnyObject>> = Array<Dictionary<String, AnyObject>>()

    if objetDTO.LstImagen != nil && objetDTO.LstImagen!.count > 0 {
        for imagenTmp in objetDTO.LstImagen! {

            let parametersImagen: Dictionary<String, AnyObject> =  ["Image Ord":imagenTmp.OrdImagen as AnyObject,"NameImg":imagenTmp.nameImg as AnyObject, "ImageType": imagenTmp.TipImagen as AnyObject, "base64Img": imagenTmp.archv as AnyObject]

            parametersImagenes.append(parametersImagen)
        }

    }


    let params: Dictionary<String, AnyObject> = [ "param1" : objetDTO.param1 as AnyObject, "param2" : objetDTO.param2 as AnyObject, "LstImagen": parametersImagenes as AnyObject]


    let urlString = "\(miURLservice)"
    let url = URL.init(string: urlString)



    Alamofire.request(url!, method: .post, parameters: params , encoding: JSONEncoding.default, headers: headers()).responseJSON { response in

        let res = response.data
        switch response.result
        {
        case .success(let json):
            DispatchQueue.main.async {
                let jsonData = json as! NSDictionary
                print(jsonData)


                let decoder = JSONDecoder()
                self.ObjResponseDTO = try! decoder.decode(ObjectDTOResponseCustom.self, from: res!)

                print("cotResponse")
                // continue.....
            }

            break
        case .failure(let error):
            //self.errorFailer(error: error)
            print(error)

            break
        }
    }
}

 func headers()->HTTPHeaders{
    return ["Authorization": " \(String(describing: kajndjasndlasjkdnasjkdnsajkdnsajkndasjkd))",
            "Content-Type": "application/json"] as HTTPHeaders
}