Skip to content

Instantly share code, notes, and snippets.

@codePrincess
Created August 3, 2017 15:00
Show Gist options
  • Save codePrincess/39e9d40dc4f211a6e1e440459081bf2f to your computer and use it in GitHub Desktop.
Save codePrincess/39e9d40dc4f211a6e1e440459081bf2f to your computer and use it in GitHub Desktop.
call the handwriten recognition for an image
public func retrieveTextOnImage(_ image: UIImage, completion: @escaping (String?, NSError?) -> ()) {
assert(CognitiveServicesComputerVisionAPIKey.characters.count > 0,
"Please set the value of the API key variable (CognitiveServicesVisualFeaturesAPIKey) before attempting to use the application.")
var urlString = CognitiveServicesConfiguration.HandwrittenOcrURL
urlString += "?\(CognitiveServicesHTTPParameters.Handwriting)=true"
let url = URL(string: urlString)
print("calling the following URL: \(String(describing: url))")
let request = NSMutableURLRequest(url: url!)
request.addValue(CognitiveServicesComputerVisionAPIKey,
forHTTPHeaderField: CognitiveServicesHTTPHeader.SubscriptionKey)
request.addValue(CognitiveServicesHTTPContentType.OctetStream,
forHTTPHeaderField: CognitiveServicesHTTPHeader.ContentType)
let requestData = UIImageJPEGRepresentation(image,
CognitiveServicesConfiguration.JPEGCompressionQuality)
request.httpBody = requestData
request.httpMethod = CognitiveServicesHTTPMethod.POST
let session = URLSession.shared
let task = session.dataTask(with: request as URLRequest) { (data, response, error) in
print("executed task")
if let error = error {
completion(nil, error as NSError?)
return
}
let headerFields = (response as! HTTPURLResponse).allHeaderFields
let operationID = headerFields["Operation-Location"] as? String
if let opID = operationID {
completion(opID, nil)
} else {
completion(nil, nil)
}
}
task.resume()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment