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.92 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.  
  11. request.httpBody = bodyData.data(using: String.Encoding.utf8)
  12.  
  13. request.addValue("##########", forHTTPHeaderField: "apikey")
  14.  
  15. let task: URLSessionDataTask = session.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) -> Void in
  16.  
  17. if let response = response {
  18. print("RESPONSE: ", response)
  19. } else {
  20. print("ERROR: No response")
  21. }
  22.  
  23. if let error = error {
  24. print("ERROR: ", error)
  25. } else {
  26. print("No error")
  27. }
  28.  
  29. do {
  30.  
  31. let dictionary = try JSONSerialization.jsonObject(with: data!, options: []) as! [String: Any]
  32.  
  33. for (key, value) in dictionary {
  34. print("Key: ", key)
  35. print("Value: ", value)
  36. }
  37.  
  38. if let parsedResults = dictionary["ParsedResults"] as? [[String: Any]] {
  39. if let parsedResult = parsedResults.first {
  40. if let parsedText = parsedResult["ParsedText"] as? String {
  41. print("PARSED TEXT ", parsedText)
  42. } else {
  43. print("ERROR: Could not read parsedText")
  44. }
  45. } else {
  46. print("ERROR: Could not read first element of parsedResult")
  47. }
  48. } else {
  49. print("ERROR: Could not read parsedResult")
  50. }
  51.  
  52. } catch let error {
  53. print("ERROR: Could not serialize jSON Data: (error.localizedDescription)")
  54. }
  55. })
  56. task.resume()
Add Comment
Please, Sign In to add comment