-
Notifications
You must be signed in to change notification settings - Fork 71
/
ocrapi.m
59 lines (48 loc) · 3.03 KB
/
ocrapi.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
- (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;
}