Guest User

Untitled

a guest
Dec 18th, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. let bitmapRep = NSBitmapImageRep(cgImage: image)
  2. let imageData = bitmapRep.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [:])! as Data
  3. let imageString = imageData.base64EncodedString(options: .endLineWithCarriageReturn)
  4.  
  5. let url = URL(string: "https://api.ocr.space/parse/image")!
  6.  
  7. let session = URLSession.shared
  8. var request = URLRequest(url: url)
  9. request.httpMethod = "POST"
  10. request.httpBody = bodyData.data(using: String.Encoding.utf8)
  11. request.addValue("##########", forHTTPHeaderField: "apikey")
  12.  
  13. let task: URLSessionDataTask = session.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) -> Void in
  14. if let response = response {
  15. print("RESPONSE: ", response)
  16. } else {
  17. print("ERROR: No response")
  18. }
  19.  
  20. if let error = error {
  21. print("ERROR: ", error)
  22. } else {
  23. print("No error")
  24. }
  25.  
  26. do {
  27. let dictionary = try JSONSerialization.jsonObject(with: data!, options: []) as! [String: Any]
  28.  
  29. for (key, value) in dictionary {
  30. print("Key: ", key)
  31. print("Value: ", value)
  32. }
  33.  
  34. if let parsedResults = dictionary["ParsedResults"] as? [[String: Any]] {
  35. if let parsedResult = parsedResults.first {
  36. if let parsedText = parsedResult["ParsedText"] as? String {
  37. print("PARSED TEXT ", parsedText)
  38. } else {
  39. print("ERROR: Could not read parsedText")
  40. }
  41. } else {
  42. print("ERROR: Could not read first element of parsedResult")
  43. }
  44. } else {
  45. print("ERROR: Could not read parsedResult")
  46. }
  47. } catch let error {
  48. print("ERROR: Could not serialize jSON Data: (error.localizedDescription)")
  49. }
  50. })
  51. task.resume()
Add Comment
Please, Sign In to add comment