Swift:如何在post请求中为body创建实际的JSON

时间:2018-05-09 09:45:20

标签: ios swift

我无法弄清楚如何在swift中构造这个JSON结构。我尝试使用字典和数组,并查看StackOverflow的类似问题,但它们并没有解决我的问题。

    {
  "requests": [
    {
      "image": {
        "content": "/9j/7QBEUGhvdG9zaG9...base64-encoded-image-content...fXNWzvDEeYxxxzj/Coa6Bax//Z"
      },
      "features": [
        {
          "type": "TEXT_DETECTION"
        }
      ]
    }
  ]
}

尝试过这样的事情:

let request = [["image":["content":"base64endocedString"]],
                   ["type":"TEXT_DETECTION"]]

    let dictionary : [String : Any] = [
        "requests":request
    ] 

输出:

[
  "requests": [
    [
      "image": [
        "content": "base64endocedString"
      ]
    ],
    [
      "type": "TEXT_DETECTION"
    ]
  ]
]

1 个答案:

答案 0 :(得分:1)

我认为您正在使用Google Vision API从图像创建请求OCR数据。您应该按以下方式使用它:

    let parameters: [String: AnyObject] = [
            "requests": [
                "image": ["content": base64EncodeImage(image)],
                "features": [ "type": "TEXT_DETECTION" ],
            ]
        ] as [String: AnyObject]

对我来说,我还需要FACE_DETECTION,所以它是:

    let header: [String: String] = ["Content-Type": "application/json",
                                    "X-Ios-Bundle-Identifier": Bundle.main.bundleIdentifier ?? ""]

    let param: [String: AnyObject] = [ "requests": [
            "image": [
                "content": base64EncodeImage(image)
            ],
            "features": [
                [
                    "type": "DOCUMENT_TEXT_DETECTION",
                    "maxResults": 10
                ],
                [
                    "type": "FACE_DETECTION",
                    "maxResults": 10
                ]
            ]
        ] ] as [String: AnyObject]

func base64EncodeImage的位置:

func base64EncodeImage(_ image: UIImage) -> String {
    let imagedata = image.resizeImageToUploadOnServer(maxSizeInKB: 2048)
    return imagedata.base64EncodedString(options: .endLineWithCarriageReturn)
}

使用此扩展程序调整图片大小:

extension UIImage {
    func resizeImageToUploadOnServer(maxSizeInKB: Int) -> Data {
        print("\(self.size)")

        let (imageSize, imageData) = self.logImageSizeInKB(scale: 1.0)
        if imageSize > maxSizeInKB {
            let resizedImage = self.reSizeImage()
            var scale: CGFloat = 1.0
            var (size, imageData) = resizedImage.logImageSizeInKB(scale: scale)
            while size > maxSizeInKB {
                scale -= 0.1
                if scale > 0 {
                    (size, imageData) = resizedImage.logImageSizeInKB(scale: scale)
                } else {
                    break
                }
                return imageData
            }
        }
        return imageData
    }

    func logImageSizeInKB(scale: CGFloat) -> (Int, Data) {
        let data = UIImageJPEGRepresentation(self, scale)!
        let formatter = ByteCountFormatter()
        formatter.allowedUnits = ByteCountFormatter.Units.useKB
        formatter.countStyle = ByteCountFormatter.CountStyle.file
        let imageSize = formatter.string(fromByteCount: Int64(data.count))
        print("ImageSize(KB): \(imageSize)")

        return (Int(Int64(data.count) / 1024), data)
    }

    func reSizeImage() -> UIImage {
        var actualHeight = Float(self.size.height)
        var actualWidth = Float(self.size.width)
        let maxHeight: Float = 2000.0
        let maxWidth: Float = 2000.0
        var imgRatio: Float = actualWidth / actualHeight
        let maxRatio: Float = maxWidth / maxHeight
        let compressionQuality: CGFloat = 1.0
        if actualHeight > maxHeight || actualWidth > maxWidth {
            if imgRatio < maxRatio {
                //adjust width according to maxHeight
                imgRatio = maxHeight / actualHeight
                actualWidth = imgRatio * actualWidth
                actualHeight = maxHeight
            } else if imgRatio > maxRatio {
                //adjust height according to maxWidth
                imgRatio = maxWidth / actualWidth
                actualHeight = imgRatio * actualHeight
                actualWidth = maxWidth
            } else {
                actualHeight = maxHeight
                actualWidth = maxWidth
            }
        }
        let rect = CGRect(x: 0.0, y: 0.0, width: CGFloat(actualWidth), height: CGFloat(actualHeight))
        UIGraphicsBeginImageContext(rect.size)
        self.draw(in: rect)

        let img = UIGraphicsGetImageFromCurrentImageContext()!
        let imageData: Data = UIImageJPEGRepresentation(img, compressionQuality)!
        UIGraphicsEndImageContext()

        return UIImage(data: imageData)!
    }
}