POST base64 для веб-API с использованием Swift 4

54
5

Я пытаюсь сделать вызов API OCR.space, загрузив изображение базы 64, но я продолжаю получать этот ответ:

Недействительный образ base64. Принятый формат изображения base64 - это "данные: image/; base64",

Я проверил изображение много раз, чтобы убедиться, что он правильно закодирован в базовом 64 формате. Правильно ли настрою URLRequest?

Вот код:

func extractTextFromImage(_ image: CGImage) {

let bitmapRep = NSBitmapImageRep(cgImage: image)
let imageData = bitmapRep.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [:])! as Data
let imageString = imageData.base64EncodedString(options: .endLineWithCarriageReturn)

let url = URL(string: "https://api.ocr.space/parse/image")!

let session = URLSession.shared
var request = URLRequest(url: url)
request.httpMethod = "POST"

request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("6ea787d56088957", forHTTPHeaderField: "apikey")

var parameters = ["base64image": [ "content_type": "image/jpeg", "base64": imageString]]

do {
let jsonData = try JSONSerialization.data(withJSONObject: parameters, options: [])
let theJSONText = String(data: jsonData, encoding: String.Encoding.utf8)
print("JSON string = \(theJSONText)")
request.httpBody = jsonData
} catch {
print(error.localizedDescription)
print("ERROR: Could not convert dictionary to JSON")
return
}

request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("6ea787d56088957", forHTTPHeaderField: "apikey")

let task: URLSessionDataTask = session.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) -> Void in

if let response = response {
print("RESPONSE: ", response)
} else {
print("ERROR: No response")
}

if let error = error {
print("ERROR: ", error)
} else {
print("No error")
}

do {

let dictionary = try JSONSerialization.jsonObject(with: data!, options: []) as! [String: Any]

for (key, value) in dictionary {
print("Key: ", key)
print("Value: ", value)
}

if let parsedResults = dictionary["ParsedResults"] as? [[String: Any]] {
if let parsedResult = parsedResults.first {
if let parsedText = parsedResult["ParsedText"] as? String {
print("PARSED TEXT ", parsedText)
} else {
print("ERROR: Could not read parsedText")
}
} else {
print("ERROR: Could not read first element of parsedResult")
}
} else {
print("ERROR: Could not read parsedResult")
}

} catch let error {
print("ERROR: Could not serialize jSON Data: \(error.localizedDescription)")
}
})
task.resume()
}

спросил(а) 2017-12-19T01:01:00+03:00 2 года, 6 месяцев назад
1
Решение
54

После многого чтения и поиска, это код, который я получил для работы:

    ///
/// Extracts the text from the given image by placing a call to the OCR.space web api
///
func extractText(from image: CGImage) {

let bitmapRep = NSBitmapImageRep(cgImage: image)
let imageData = bitmapRep.representation(using: NSBitmapImageRep.FileType.png, properties: [:])! as Data

let url = URL(string: "https://api.ocr.space/parse/image")!

let session = URLSession.shared
var request = URLRequest(url: url)
request.httpMethod = "POST"

let boundary = "--------69-69-69-69-69"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("6ea787d56088957", forHTTPHeaderField: "apikey")
request.httpBody = createBody(parameters: nil, filePathKey: "file", imageDataKey: imageData, boundary: boundary)

let task = session.synchronousDataTask(urlrequest: request)
let data = task.0
let error = task.2

if data == nil {
print("ERROR: No response from OCR.space api call")
return
}

if error != nil {
print("ERROR: ", error!)
return
}

do {
let dictionary = try JSONSerialization.jsonObject(with: data!, options: []) as! [String: Any]

if let parsedResults = dictionary["ParsedResults"] as? [[String: Any]] {
if let parsedResult = parsedResults.first {
if let text = parsedResult["ParsedText"] as? String {
parsedText = text
return
} else {
print("ERROR: Could not read parsedText")
return
}
} else {
print("ERROR: Could not read first element of parsedResult")
return
}
} else {
print("ERROR: Could not read parsedResult")
return
}
} catch let error {
print("ERROR: Could not serialize jSON Data into dictionary: \(error.localizedDescription)")
return
}
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

///
/// Creates a the body of the url request using the given parameters
///
private func createBody(parameters: [String: String]?, filePathKey: String?, imageDataKey: Data, boundary: String) -> Data {
var body = Data();

if parameters != nil {
for (key, value) in parameters! {
body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n".data(using: String.Encoding.utf8)!)
body.append("\(value)\r\n".data(using: String.Encoding.utf8)!)
}
}

let filename = "image.jpg"
let mimetype = "image/jpg"

body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Type: \(mimetype)\r\n\r\n".data(using: String.Encoding.utf8)!)
body.append(imageDataKey)
body.append("\r\n".data(using: String.Encoding.utf8)!)

body.append("--\(boundary)--\r\n".data(using: String.Encoding.utf8)!)

return body
}

ответил(а) 2018-03-22T07:44:00+03:00 2 года, 3 месяца назад
Ваш ответ
Введите минимум 50 символов
Чтобы , пожалуйста,
Выберите тему жалобы:

Другая проблема