Permalink
Find file
3013faf Feb 29, 2016
60 lines (48 sloc) 3.03 KB
- (void)callOCRSpace {
// Create URL request
NSURL *url = [NSURL URLWithString:@"https://api.ocr.space/Parse/Image"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"randomString";
[request addValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary] forHTTPHeaderField:@"Content-Type"];
NSURLSession *session = [NSURLSession sharedSession];
// Image file and parameters
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"yourImage"], 0.6);
NSDictionary *parametersDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
@"yourKey", @"apikey",
@"True", @"isOverlayRequired",
@"eng", @"language", nil];
// Create multipart form body
NSData *data = [self createBodyWithBoundary:boundary
parameters:parametersDictionary
imageData:imageData
filename:@"yourImage.jpg"];
[request setHTTPBody:data];
// Start data session
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSError* myError;
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&myError];
// Handle result
}];
[task resume];
}
- (NSData *) createBodyWithBoundary:(NSString *)boundary parameters:(NSDictionary *)parameters imageData:(NSData*)data filename:(NSString *)filename
{
NSMutableData *body = [NSMutableData data];
if (data) {
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", @"file", filename] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:data];
[body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
for (id key in parameters.allKeys) {
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"%@\r\n", parameters[key]] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
return body;
}