How to add string and array - ios

NSString *butterfly = [NSString stringWithFormat:#"brush_%d.png", i]
I want that string in separate like this
brush_
%d.png
Because i have lot of animation function are there in my project(0 to 39).
if(counter == 0) {
NSMutableArray *dashBoy = [NSMutableArray array];
for (i = 1; i<= 13; i++) {
butterfly = [NSString stringWithFormat:#"brush_%d.png", i];
if ((image = [UIImage imageNamed:butterfly]))
[dashBoy addObject:image];
}
[stgImageView setAnimationImages:dashBoy];
[stgImageView setAnimationDuration:2.0f];
[stgImageView startAnimating];
}
.
.
if(counter == 39) {
NSMutableArray *dashBoy1 = [NSMutableArray array];
for (i = 1; i <= 30; i++) {
butterfly = [NSString stringWithFormat:#"catch_%d.png", i];
if ((image = [UIImage imageNamed:butterfly]))
[dashBoy1 addObject:image];
}
[stgImageView setAnimationImages:dashBoy1];
[stgImageView setAnimationDuration:7.20f];
[stgImageView startAnimating];
}
I tried this but it's not correct
NSArray *c = [NSArray arrayWithObjects:#"brush", #"catch", #"clap",#"dog", nil];
//NSString *str = #"brush_";
NSString *str = [c componentsJoinedByString:#""];
for (int i=0; i<=3;i++)
str = [str stringByAppendingFormat:#"_%i.png ",i];
NSLog(#"%#",str); //Output is brushcatchclapdog_0.png _1.png _2.png _3.png
I want
brush_0.png, catch_1.png, clap_2.png in array
Here i want to combine in one function using for loop above category.It is possible to get one function to combine the above 39 animation function.

[self animateWithCategory:#"brush_" WithCount:13 duration:0.2f]
-(void)animateWithCategory:(NSString *)strCategory WithCount:(CGFloat)count duration:(NSInteger)duration{
NSMutableArray *dashBoy = [NSMutableArray array];
for (int i = 1; i<= count; i++) {
NSString* butterfly = [NSString stringWithFormat:#"%#%d.png",strCategory ,i];
UIImage *image=[UIImage imageNamed:butterfly];
[dashBoy addObject:image];
}
[stgImageView setAnimationImages:dashBoy];
[stgImageView setAnimationDuration:duration];
[stgImageView setAnimationRepeatCount:1];
[stgImageView startAnimating];
}

As per your desired output:
I want
brush_0.png, catch_1.png, clap_2.png in array
you can try like this:
NSArray *c = [NSArray arrayWithObjects:#"brush", #"catch", #"clap",#"dog", nil];
NSMutableArray *o = [[NSMutableArray alloc] initWithCapacity:[c count]];
//NSString *str = #"brush_";
//NSString *str = [c componentsJoinedByString:#""];
for (int i=0; i<=3;i++)
{
NSString *str = [[c objectAtIndex:i] stringByAppendingFormat:#"_%i.png ",i];
NSLog(#"%#",str); //Output is brushcatchclapdog_0.png _1.png _2.png _3.png
[o addObject:str];
}//brush_0.png, catch_1.png, clap_2.png in array
NSLog(#"Output array : %#", o);
Logged output of the code:
2014-02-07 00:31:29.020 DesignMantic[807:70b] brush_0.png
2014-02-07 00:31:29.023 DesignMantic[807:70b] catch_1.png
2014-02-07 00:31:29.024 DesignMantic[807:70b] clap_2.png
2014-02-07 00:31:29.025 DesignMantic[807:70b] dog_3.png
2014-02-07 00:31:29.026 DesignMantic[807:70b] Output array : (
"brush_0.png ",
"catch_1.png ",
"clap_2.png ",
"dog_3.png "
)

Related

Setting Timeout as Activity indicator keeps spinning when there is no response from webservice

I am using REST API to fetch data. I have two methods, one for ResponceSucces and other for responceFailure. In responce failure I simply dismiss the activity indicator. Sometimes it happens that data is not retrieved but still activity indicator keeps spinning infinitely. And ResponceFailure method is not Called.
My question is can I set timeout interval to my web service, to check if response did not come, then activity indicator must be dismissed after some time for example 20/30 seconds.
Below is my code:
-(void)messagesGetSuccess:(FBListingsWebHandler*)handler response:(NSDictionary*)response
{
[MBProgressHUD hideHUDForView:self.view animated:YES];
[[FBModelManager sharedModelManager].messages removeAllObjects];
NSArray *messagesArray = [response objectForKey:#"message"];
if([[FBUserManager sharedUserManager] userType] == kUserShipper){
//extract usernames of transporters who placed bid on selected listing
NSArray *userNames;
NSMutableArray *transporterNames;
NSDictionary *biddingsDic = [[FBModelManager sharedModelManager] getModelDictionary:kModelBiddings];
if ([biddingsDic count] > 0){
userNames = [[biddingsDic allValues] valueForKey:#"userName"];
NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:userNames];
NSSet *uniqueNames = [orderedSet set];
transporterNames = [[NSMutableArray alloc] initWithArray:[uniqueNames allObjects]];
}
//add transporter records in messages dictionary who have messages for selected listing
for (int i = 1; i < [messagesArray count]; i++) {
NSMutableArray *modelArray = [[NSMutableArray alloc] init];
NSDictionary *groupedMsgDic = [messagesArray objectAtIndex:i];
int count = (int)[[[groupedMsgDic allValues] objectAtIndex:0] count];
for (int j = 0; j < count; j++) {
FBMessagesModel *model = [[FBMessagesModel alloc] initWithMessageItems:[[[groupedMsgDic allValues] objectAtIndex:0] objectAtIndex:j]];
[modelArray addObject:model];
model = nil;
}
[[FBModelManager sharedModelManager].messages setObject:modelArray forKey:[[groupedMsgDic allKeys] objectAtIndex:0]];
//remove transporter usernames from array who have messages besides bid for selected listing
if([transporterNames containsObject:[[groupedMsgDic allKeys] objectAtIndex:0]]){
[transporterNames removeObject:[[groupedMsgDic allKeys] objectAtIndex:0]];
}
modelArray = nil;
}
//add transporter records in messages dictionary who placed bid but have no message for selected listing
for (int i = 0; i < [transporterNames count]; i++) {
NSString *path = [[[biddingsDic allValues] objectAtIndex:[userNames indexOfObject:[transporterNames objectAtIndex:i]]] photoPath];
int transporterId = [[[biddingsDic allValues] objectAtIndex:[userNames indexOfObject:[transporterNames objectAtIndex:i]]] userId];
NSString *objectForZeroMsgs = [NSString stringWithFormat:#"%#-%d",path,transporterId];
[[FBModelManager sharedModelManager].messages setObject:objectForZeroMsgs forKey:[transporterNames objectAtIndex:i]];
}
transporterNames = nil;
// [self tableView:self.shipperGroupedMessagesTableView_ numberOfRowsInSection:0];
[self.shipperGroupedMessagesTableView_ reloadData];
}else if([[FBUserManager sharedUserManager] userType] == kUserTransporter){
for (int i = 1; i < [messagesArray count]; i++) {
FBMessagesModel *model = [[FBMessagesModel alloc] initWithMessageItems:[messagesArray objectAtIndex:i]];
[[FBModelManager sharedModelManager].messages setObject:model forKey:[NSString stringWithFormat:#"%d",model.mailId]];
if(model.mailMessage && ![model.mailMessage isEqualToString:#""]){
[self createMessageBubble:model];
}
model = nil;
}
[self.bubbleTableView_ reloadData];
}
}
-(void)messagesGetFailure:(FBListingsWebHandler*)handler
{
[MBProgressHUD hideHUDForView:self.view animated:YES];
[[FBModelManager sharedModelManager].messages removeAllObjects];
if([[FBUserManager sharedUserManager] userType] == kUserTransporter){
[self.bubbleTableView_ reloadData];
}
else if([[FBUserManager sharedUserManager] userType] == kUserShipper){
if([[FBModelManager sharedModelManager].messages count] == 0){
NSDictionary *biddingsDic = [[FBModelManager sharedModelManager] getModelDictionary:kModelBiddings];
if ([biddingsDic count] > 0){
NSArray *userNames = [[biddingsDic allValues] valueForKey:#"userName"];
NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:userNames];
NSSet *uniqueNames = [orderedSet set];
NSArray *transporterNames = [uniqueNames allObjects];
[[FBModelManager sharedModelManager].messages removeAllObjects];
for (int i = 0; i < [transporterNames count]; i++) {
NSString *path = [[[biddingsDic allValues] objectAtIndex:[userNames indexOfObject:[transporterNames objectAtIndex:i]]] photoPath];
int transporterId = [[[biddingsDic allValues] objectAtIndex:[userNames indexOfObject:[transporterNames objectAtIndex:i]]] userId];
NSString *objectForZeroMsgs = [NSString stringWithFormat:#"%#-%d",path,transporterId];
[[FBModelManager sharedModelManager].messages setObject:objectForZeroMsgs forKey:[transporterNames objectAtIndex:i]];
}
[self.shipperGroupedMessagesTableView_ reloadData];
}else{
[self addNoMessagesLabel];
}
}
[self.shipperGroupedMessagesTableView_ reloadData];
}
}
I am adding a screenshot.

(ios) CSV file to multiple arrays?

ok I'm learning to use xCode(5) and I want to use a csv file (screenshot) to read data to store into 7 separate arrays. However, I'm having problems separating the 7 values. I know I'm supposed to use "componentsSeparatedByString" in my case, by ","...but Idk where to place it. Any advice would be appreciated!
csv screenshot: http://i61.tinypic.com/qz5ie8.png
*7th value is " ", used for other purposes.
{
[super viewDidLoad];
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
NSError *error;
NSString *allEntries = [NSString stringWithContentsOfFile:#"fighterbase.csv" encoding:NSUTF8StringEncoding error:&error];
NSArray *rows = [allEntries componentsSeparatedByString:#"\n"];
_names = [[NSMutableArray alloc] init];
_origins = [[NSMutableArray alloc] init];
_ages = [[NSMutableArray alloc] init];
_heights = [[NSMutableArray alloc] init];
_weights = [[NSMutableArray alloc] init];
_games = [[NSMutableArray alloc] init];
_images = [[NSMutableArray alloc] init];
for(int i = 0; i < [rows count]; i++)
{
[_names addObject:[rows objectAtIndex:0]];
[_origins addObject:[rows objectAtIndex:1]];
[_ages addObject:[rows objectAtIndex:2]];
[_heights addObject:[rows objectAtIndex:3]];
[_weights addObject:[rows objectAtIndex:4]];
[_games addObject:[rows objectAtIndex:5]];
[_images addObject:[rows objectAtIndex:6]];
}
NSLog(#"Name: %# Origin: %# Age:%#", [_names objectAtIndex:0], [_origins objectAtIndex:0], [_ages objectAtIndex:0]);
}
This should do the trick:
for(int i = 0; i < [rows count]; i++)
{
NSArray *arrayLine = [[row objectAtIndex:i] componentsSeparatedByString#","];
[_names addObject:[arrayLine objectAtIndex:0]];
[_origins addObject:[arrayLine objectAtIndex:1]];
[_ages addObject:[arrayLine objectAtIndex:2]];
[_heights addObject:[arrayLine objectAtIndex:3]];
[_weights addObject:[arrayLine objectAtIndex:4]];
[_games addObject:[arrayLine objectAtIndex:5]];
[_images addObject:[arrayLine objectAtIndex:6]];
}
But in your image, I didn't see there was a 7th value, which may be crash it if it doesn't exist. Well, you said "*7th value is " "", so you may want to manage it.

GCD slow updating UI

Im using GCD to download a plist file from the internet then enter the data into an array then load it into a tableView.
The data is being downloaded and converted alright but the table view is taking ages to update. I have the app Logging something when it calls [self.tableView reloadData] but the table view updates about 10 seconds later.
I don't think this is about the table view because I tried changing the title of the Navigation Bar inside the GCD and there was also a delay. So it might be a delay updating the user interface?
This is my GCD code:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
Thanks for you help
EDIT:
This is my code:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UERootArray = [[NSArray alloc] initWithContentsOfURL:[NSURL URLWithString:#"url to file"]];
NSLog(#"Array: %#", UERootArray);
//NSLog(#"count %#",count);
NSString *currentName;
NSString *currentLoaction;
NSString *currentDate;
int currentEventInt = 0;
NSArray *currentEventArr = [UERootArray objectAtIndex:0];
while (currentEventArr.count > currentEventInt)
{
currentName = [currentEventArr objectAtIndex:0];
currentLoaction = [currentEventArr objectAtIndex:1];
currentDate = #"7pm 17/11"; //[currentEventArr objectAtIndex:2];
NSLog (#"Title: %#", currentName);
NSLog (#"News: %#", currentLoaction);
NSLog (#"Date: %#", currentDate);
UEEvent *currentTask = [[UEEvent alloc] initWithName:currentName location:currentLoaction date:currentDate];
[self.upcommingEvents addObject:currentTask];
currentEventInt = currentEventInt + 1;
}
UEDownloaded = YES;
[self.tableView reloadData];
Edit 2:
- (void)downloadUEData
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UERootArray = [[NSArray alloc] initWithContentsOfURL:[NSURL URLWithString:#"url to file"]];
[self processUEData];
});
}
- (void)processUEData
{
NSLog(#"Array: %#", UERootArray);
//NSLog(#"count %#",count);
NSString *currentName;
NSString *currentLoaction;
NSString *currentDate;
int currentEventInt = 0;
NSArray *currentEventArr = [UERootArray objectAtIndex:0];
while (currentEventArr.count > currentEventInt)
{
currentName = [currentEventArr objectAtIndex:0];
currentLoaction = [currentEventArr objectAtIndex:1];
currentDate = #"7pm 17/11"; //[currentEventArr objectAtIndex:2];
NSLog (#"Title: %#", currentName);
NSLog (#"News: %#", currentLoaction);
NSLog (#"Date: %#", currentDate);
UEEvent *currentTask = [[UEEvent alloc] initWithName:currentName location:currentLoaction date:currentDate];
[self.upcommingEvents addObject:currentTask];
currentEventInt = currentEventInt + 1;
}
UEDownloaded = YES;
[self.tableView reloadData];
}
i think following code will solve your problem ...
- (void)downloadUEData
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UERootArray = [[NSArray alloc] initWithContentsOfURL:[NSURL URLWithString:#"http://www.nytrex.webs.com/Linx/upcommingEvents.plist"]];
[self processUEData];
});
}
- (void)processUEData
{
NSLog(#"Array: %#", UERootArray);
//NSLog(#"count %#",count);
NSString *currentName;
NSString *currentLoaction;
NSString *currentDate;
int currentEventInt = 0;
NSArray *currentEventArr = [UERootArray objectAtIndex:0];
while (currentEventArr.count > currentEventInt)
{
currentName = [currentEventArr objectAtIndex:0];
currentLoaction = [currentEventArr objectAtIndex:1];
currentDate = #"7pm 17/11"; //[currentEventArr objectAtIndex:2];
NSLog (#"Title: %#", currentName);
NSLog (#"News: %#", currentLoaction);
NSLog (#"Date: %#", currentDate);
UEEvent *currentTask = [[UEEvent alloc] initWithName:currentName location:currentLoaction date:currentDate];
[self.upcommingEvents addObject:currentTask];
currentEventInt = currentEventInt + 1;
}
UEDownloaded = YES;
dispatch_async(dispatch_get_main_queue(), ^{ // update your UI in main thread
[self.tableView reloadData];
});
}

Tesseract iOS camera low accuracy

When I use an image taken with the camera on the iPhone and send it to tesseract the accuracy is horrible it is all garbage text, but when I choose the same image from the photo library I get great accuracy.
How can I improve tesseracts accuracy from a picture take with the camera? Here is what I am doing to the image before sending
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
UIImage *image = info[UIImagePickerControllerOriginalImage];
CGFloat newWidth = 1200;
CGSize newSize = CGSizeMake(newWidth, newWidth);
image = [image resizedImage:newSize interpolationQuality:kCGInterpolationHigh];
Tesseract* tesseract = [[Tesseract alloc]initWithLanguage:#"eng"];
[tesseract setVariableValue:#"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ##&*()-_:." forKey:#"tessedit_char_whitelist"];
[tesseract setVariableValue:#"`~!%^*[]{}<>?|" forKey:#"tessedit_char_blacklist"];
[tesseract setImage:image];
[tesseract recognize];
NSLog(#"%#", [tesseract recognizedText]);
[picker dismissViewControllerAnimated:YES completion:NULL];
}
If anyone has found some "magical" way to get tesseract to scan with great accuracy I will reward a bounty!
Main things to consider:
Tesseract needs to be trained for the font and language being recognized.
It looks like you are supplying appropriate parameters here - are they the same that you use when you supply a predefined image?
Tesseract doesn't orientate, or 'clean up' images
When you pass an image to the library, it should already be cleaned up and in portrait. Is the
image in photo reel taken from the camera too, or is it a sample image you've saved there somehow?
One check to make is the resize function:
CGFloat newWidth = 1200;
CGSize newSize = CGSizeMake(newWidth, newWidth);
The original image will be distorted by this, since you are resizing a non-square image into a square image. This will definitely squash the text and make life difficult for Tesseract. At the very least, you want to preserve the aspect ratio of the captured image.
My code work fine, but it´s more complex
- (IBAction)captureTapped:(id)sender
{
NSMutableArray *results = [NSMutableArray array];
NSString *fullWord = #"";
OCRImplementation *ocr = [[OCRImplementation alloc] init];
for(int j = 0; j < [self.images count]; j++){
UIImage *imageToTesseract = [self.images objectAtIndex:j];
//UIImage *imageToTesseract = self.imgfinal.image;
NSMutableArray *sortedKeys = [NSMutableArray array];
#try {
sortedKeys = [ocr processImageDetectText:imageToTesseract threadhold:198];
}
#catch (NSException *exception) {
sortedKeys = [NSMutableArray array];
}
NSString *finalWord = #"";
if([sortedKeys count] > 0){
for(int i=0; i<[sortedKeys count]; i++){
UIImage *image = [sortedKeys objectAtIndex:i];
finalWord = [self confidencesOCRTesseract:image];
if(finalWord.length > 1){
finalWord = [NSString stringWithFormat:#"%c",[finalWord characterAtIndex:0]];
}
fullWord = [fullWord stringByAppendingString:finalWord];
}
}
fullWord = [fullWord stringByReplacingOccurrencesOfString:#"\n" withString:#""];
[results addObject:fullWord];
NSLog(#"-- RESULT -- %#",fullWord);
}
NSString *resultWord = #"";
if([results count] > 0){
resultWord = [self calculateStatics:results];
}
//Your text Result
NSLog(#"%#",resultWord);
}
- (NSString*)calculateStatics:(NSMutableArray*)results{
NSMutableArray *first = [NSMutableArray array];
NSMutableArray *second = [NSMutableArray array];
NSMutableArray *third = [NSMutableArray array];
NSMutableArray *fourth = [NSMutableArray array];
NSMutableArray *fifth = [NSMutableArray array];
NSMutableArray *six = [NSMutableArray array];
NSMutableArray *seven = [NSMutableArray array];
for(int i = 0; i<[results count]; i++){
NSString *result = [results objectAtIndex:i];
if(result && ![result isEqualToString:#""]){
if(result.length >= 1 && [result characterAtIndex:0]){
[first addObject:[NSString stringWithFormat:#"%c", [result characterAtIndex:0]]];
}else{
[first addObject:#" "];
}
if(result.length >= 2 &&[result characterAtIndex:1]){
[second addObject:[NSString stringWithFormat:#"%c", [result characterAtIndex:1]]];
}else{
[second addObject:#" "];
}
if(result.length >= 3 &&[result characterAtIndex:2]){
[third addObject:[NSString stringWithFormat:#"%c", [result characterAtIndex:2]]];
}else{
[third addObject:#" "];
}
if(result.length >= 4 &&[result characterAtIndex:3]){
[fourth addObject:[NSString stringWithFormat:#"%c", [result characterAtIndex:3]]];
}else{
[fourth addObject:#" "];
}
if(result.length >= 5 &&[result characterAtIndex:4]){
[fifth addObject:[NSString stringWithFormat:#"%c", [result characterAtIndex:4]]];
}else{
[fifth addObject:#" "];
}
if(result.length >= 6 &&[result characterAtIndex:5]){
[six addObject:[NSString stringWithFormat:#"%c", [result characterAtIndex:5]]];
}else{
[six addObject:#" "];
}
if(result.length >= 7 &&[result characterAtIndex:6]){
[seven addObject:[NSString stringWithFormat:#"%c", [result characterAtIndex:6]]];
}else{
[seven addObject:#" "];
}
}else{
[first addObject:#" "];
[second addObject:#" "];
[third addObject:#" "];
[fourth addObject:#" "];
[fifth addObject:#" "];
[six addObject:#" "];
[seven addObject:#" "];
}
}
NSString *word = #"";
NSCountedSet *frequencies = [NSCountedSet setWithArray:first];
if([frequencies count] == 1){
word = [word stringByAppendingString:[[frequencies allObjects] objectAtIndex:0]];
}else{
NSUInteger count = 0;
NSString *repeatedWord = #"";
for(int i=0; i<[frequencies count]; i++){
NSString *possibleWord = [[frequencies allObjects] objectAtIndex:i];
NSUInteger wordCount = [frequencies countForObject:possibleWord];
if(count < wordCount){
count = wordCount;
repeatedWord = possibleWord;
}
}
word = [word stringByAppendingString:repeatedWord];
}
NSCountedSet *frequencies2 = [NSCountedSet setWithArray:second];
if([frequencies2 count] == 1){
word = [word stringByAppendingString:[[frequencies2 allObjects] objectAtIndex:0]];
}else{
NSUInteger count = 0;
NSString *repeatedWord = #"";
for(int i=0; i<[frequencies2 count]; i++){
NSString *possibleWord = [[frequencies2 allObjects] objectAtIndex:i];
NSUInteger wordCount = [frequencies2 countForObject:possibleWord];
if(count < wordCount){
count = wordCount;
repeatedWord = possibleWord;
}
}
word = [word stringByAppendingString:repeatedWord];
}
NSCountedSet *frequencies3 = [NSCountedSet setWithArray:third];
if([frequencies3 count] == 1){
word = [word stringByAppendingString:[[frequencies3 allObjects] objectAtIndex:0]];
}else{
NSUInteger count = 0;
NSString *repeatedWord = #"";
for(int i=0; i<[frequencies3 count]; i++){
NSString *possibleWord = [[frequencies3 allObjects] objectAtIndex:i];
NSUInteger wordCount = [frequencies3 countForObject:possibleWord];
if(count < wordCount){
count = wordCount;
repeatedWord = possibleWord;
}
}
word = [word stringByAppendingString:repeatedWord];
}
NSCountedSet *frequencies4 = [NSCountedSet setWithArray:fourth];
if([frequencies4 count] == 1){
word = [word stringByAppendingString:[[frequencies4 allObjects] objectAtIndex:0]];
}else{
NSUInteger count = 0;
NSString *repeatedWord = #"";
for(int i=0; i<[frequencies4 count]; i++){
NSString *possibleWord = [[frequencies4 allObjects] objectAtIndex:i];
NSUInteger wordCount = [frequencies4 countForObject:possibleWord];
if(count < wordCount){
count = wordCount;
repeatedWord = possibleWord;
}
}
word = [word stringByAppendingString:repeatedWord];
}
NSCountedSet *frequencies5 = [NSCountedSet setWithArray:fifth];
if([frequencies5 count] == 1){
word = [word stringByAppendingString:[[frequencies5 allObjects] objectAtIndex:0]];
}else{
NSUInteger count = 0;
NSString *repeatedWord = #"";
for(int i=0; i<[frequencies5 count]; i++){
NSString *possibleWord = [[frequencies5 allObjects] objectAtIndex:i];
NSUInteger wordCount = [frequencies5 countForObject:possibleWord];
if(count < wordCount){
count = wordCount;
repeatedWord = possibleWord;
}
}
word = [word stringByAppendingString:repeatedWord];
}
NSCountedSet *frequencies6 = [NSCountedSet setWithArray:six];
if([frequencies6 count] == 1){
word = [word stringByAppendingString:[[frequencies6 allObjects] objectAtIndex:0]];
}else{
NSUInteger count = 0;
NSString *repeatedWord = #"";
for(int i=0; i<[frequencies6 count]; i++){
NSString *possibleWord = [[frequencies6 allObjects] objectAtIndex:i];
NSUInteger wordCount = [frequencies6 countForObject:possibleWord];
if(count < wordCount){
count = wordCount;
repeatedWord = possibleWord;
}
}
word = [word stringByAppendingString:repeatedWord];
}
NSCountedSet *frequencies7 = [NSCountedSet setWithArray:seven];
if([frequencies7 count] == 1){
word = [word stringByAppendingString:[[frequencies7 allObjects] objectAtIndex:0]];
}else{
NSUInteger count = 0;
NSString *repeatedWord = #"";
for(int i=0; i<[frequencies7 count]; i++){
NSString *possibleWord = [[frequencies7 allObjects] objectAtIndex:i];
NSUInteger wordCount = [frequencies7 countForObject:possibleWord];
if(count < wordCount){
count = wordCount;
repeatedWord = possibleWord;
}
}
word = [word stringByAppendingString:repeatedWord];
}
return word;
}
OCRImplementation class
OCRImplementation.h
#ifndef __TesseractSample__OCRImplementation__
#define __TesseractSample__OCRImplementation__
#endif /* defined(__TesseractSample__OCRImplementation__) */
#interface OCRImplementation : NSObject{
}
- (UIImage*)processImage:(id)sender;
- (NSString*)confidencesOCRTesseract:(UIImage*)picture;
#end
OCRImplementation.mm
#include "OCRImplementation.h"
#import <OpenCV/opencv2/imgproc/imgproc.hpp>
#import <OpenCV/opencv2/highgui/highgui.hpp>
#import "UIImage+OpenCV.h"
#import "Tesseract.h"
#import "baseapi.h"
#import "environ.h"
#import "pix.h"
#include <sstream>
#include <iostream>
#include <vector>
#include "OpenCV/opencv2/core/core.hpp"
#include "OpenCV/opencv2/features2d/features2d.hpp"
#include "OpenCV/opencv2/calib3d/calib3d.hpp"
#implementation OCRImplementation
- (NSMutableArray*)processImageDetectText:(id)sender threadhold:(int)threadhold{
UIImage *img1 = sender;
cv::Mat src = [img1 CVMat];
cv::Mat src_gray;
cv::Mat threshold_output;
cv::vector<cv::vector<cv::Point> > contours;
cv::vector<cv::Vec4i> hierarchy;
int thresh = 100;
cv::RNG rng(12345);
/// Convert image to gray and blur it
cvtColor( src, src_gray, CV_BGR2GRAY );
blur( src_gray, src_gray, cv::Size(3,3) );
/// Detect edges using Threshold
cv::threshold( src_gray, threshold_output, thresh, 255, cv::THRESH_BINARY );
/// Find contours
cv::findContours( threshold_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0) );
/// Approximate contours to polygons + get bounding rects and circles
cv::vector<cv::vector<cv::Point> > contours_poly( contours.size() );
cv::vector<cv::Rect> boundRect( contours.size() );
cv::vector<cv::Point2f>center( contours.size() );
cv::vector<float>radius( contours.size() );
for( int i = 0; i < contours.size(); i++ )
{
approxPolyDP( cv::Mat(contours[i]), contours_poly[i], 3, true );
boundRect[i] = boundingRect( cv::Mat(contours_poly[i]) );
minEnclosingCircle( (cv::Mat)contours_poly[i], center[i], radius[i] );
}
/// Draw polygonal contour + bonding rects + circles
cv::Mat drawing = cv::Mat::zeros( threshold_output.size(), CV_8UC3 );
NSMutableDictionary *dictionaryImages = [NSMutableDictionary dictionary];
NSMutableArray *areaArray = [NSMutableArray array];
float lastArea = 0.0;
for( int i = 0; i< contours.size(); i++ )
{
cv::Scalar color = cv::Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) );
if(boundRect[i].height > 50){
double area = cv::contourArea(contours[i]);
if((boundRect[i].width < boundRect[i].height) && area > (lastArea / 2)){
lastArea = area;
[areaArray addObject:[NSString stringWithFormat:#"%f",area]];
rectangle( drawing, boundRect[i].tl(), boundRect[i].br(), color, 2, 8, 0 );
cv::Rect extendedRect = cv::Rect(boundRect[i].x - 5, boundRect[i].y - 5, boundRect[i].width + 10, boundRect[i].height + 10);
cv::Mat source = src;
cv::Mat target(extendedRect.size(), source.type());
if(0 <= extendedRect.x && 0 <= extendedRect.width && extendedRect.x + extendedRect.width <= source.cols && 0 <= extendedRect.y && 0 <= extendedRect.height && extendedRect.y + extendedRect.height <= source.rows){
source(extendedRect).copyTo(target);
//converting the original image into grayscale
cv::cvtColor(target, target, CV_BGR2GRAY);
cv::multiply(target, cv::Scalar(2,2,2), target);
cv::add(target, cv::Scalar(2,2,2), target);
/// Detect edges using Threshold
cv::threshold( target, threshold_output, threadhold, 255, cv::THRESH_BINARY );
cv::dilate(threshold_output, threshold_output, NULL);
UIImage *imgFinal = [OCRImplementation imageWithCVMat:threshold_output];
[dictionaryImages setObject:imgFinal forKey:[NSString stringWithFormat:#"%f", area]];
}else{
NSLog(#"Error al leer la imagen. NO ROI");
}
}
}
}
NSMutableDictionary *finalImages = [NSMutableDictionary dictionary];
NSMutableArray *sortedKeys = [NSMutableArray arrayWithArray:[areaArray sortedArrayUsingFunction:intSort context:NULL]];
for( int k = 0; k< contours.size(); k++ )
{
if(boundRect[k].height > 50){
for(int i = 0; i < [sortedKeys count]; i++){
double area = cv::contourArea(contours[k]);
if(area == [[sortedKeys objectAtIndex:i] floatValue]){
[finalImages setObject:[dictionaryImages objectForKey:[sortedKeys objectAtIndex:i]] forKey:[NSString stringWithFormat:#"%d",boundRect[k].x]];
}
}
}
}
NSMutableArray *array = [NSMutableArray array];
NSArray *keys = [finalImages allKeys];
NSArray *sortedKeys2 = [keys sortedArrayUsingFunction:intSortDesc context:NULL];
for(int i=0; i<[sortedKeys2 count]; i++){
[array addObject:[finalImages objectForKey:[sortedKeys2 objectAtIndex:i]]];
}
return array;
}
+ (UIImage *)imageWithCVMat:(const cv::Mat&)cvMat
{
NSData *data = [NSData dataWithBytes:cvMat.data length:cvMat.elemSize() * cvMat.total()];
CGColorSpaceRef colorSpace;
if (cvMat.elemSize() == 1) {
colorSpace = CGColorSpaceCreateDeviceGray();
} else {
colorSpace = CGColorSpaceCreateDeviceRGB();
}
CGDataProviderRef provider = CGDataProviderCreateWithCFData((CFDataRef)data);
CGImageRef imageRef = CGImageCreate(cvMat.cols, // Width
cvMat.rows, // Height
8, // Bits per component
8 * cvMat.elemSize(), // Bits per pixel
cvMat.step[0], // Bytes per row
colorSpace, // Colorspace
kCGImageAlphaNone | kCGBitmapByteOrderDefault, // Bitmap info flags
provider, // CGDataProviderRef
NULL, // Decode
false, // Should interpolate
kCGRenderingIntentDefault); // Intent
UIImage *image = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
CGDataProviderRelease(provider);
CGColorSpaceRelease(colorSpace);
return image;
}
- (NSString*)confidencesOCRTesseract:(UIImage*)picture{
tesseract::TessBaseAPI* tess;
uint32_t* _pixels;
NSString* _dataPath = #"tessdata";
NSString* _language = #"eng";
// Useful paths
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = ([documentPaths count] > 0) ? [documentPaths objectAtIndex:0] : nil;
NSString *dataPath = [documentPath stringByAppendingPathComponent:_dataPath];
// Copy data in Doc Directory
if (![fileManager fileExistsAtPath:dataPath]) {
NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
NSString *tessdataPath = [bundlePath stringByAppendingPathComponent:_dataPath];
if (tessdataPath) {
[fileManager copyItemAtPath:tessdataPath toPath:dataPath error:nil];
}
}
setenv("TESSDATA_PREFIX", [[documentPath stringByAppendingString:#"/"] UTF8String], 1);
tess = new tesseract::TessBaseAPI();
tess->Init([_dataPath UTF8String], [_language UTF8String]);
tess->SetVariable("save_blob_choices", "T");
tess->SetVariable("tessedit_char_whitelist", "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
//SET IMAGE
CGSize size = [picture size];
int width = size.width;
int height = size.height;
_pixels = (uint32_t *) malloc(width * height * sizeof(uint32_t));
// Clear the pixels so any transparency is preserved
memset(_pixels, 0, width * height * sizeof(uint32_t));
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
// Create a context with RGBA _pixels
CGContextRef context = CGBitmapContextCreate(_pixels, width, height, 8, width * sizeof(uint32_t), colorSpace,
kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedLast);
// Paint the bitmap to our context which will fill in the _pixels array
CGContextDrawImage(context, CGRectMake(0, 0, width, height), [picture CGImage]);
// We're done with the context and color space
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
tess->SetImage((const unsigned char *) _pixels, width, height, sizeof(uint32_t), width * sizeof(uint32_t));
//END SET IMAGE
tess->Recognize(NULL);
tesseract::ResultIterator* ri = tess->GetIterator();
tesseract::ChoiceIterator* ci;
// For every identified symbol (there should be only one...)
NSString *finalWord = #"";
if(ri != 0) {
do {
const char* symbol = ri->GetUTF8Text(tesseract::RIL_SYMBOL);
if(symbol != 0) {
float conf = ri->Confidence(tesseract::RIL_SYMBOL);
if(conf > 80.0f){
finalWord = [finalWord stringByAppendingString:[NSString stringWithUTF8String:symbol]];
}else{
const tesseract::ResultIterator itr = *ri;
ci = new tesseract::ChoiceIterator(itr);
// For every chosen candidate...
do {
const char* choice = ci->GetUTF8Text();
NSString *choiceStr = [NSString stringWithUTF8String:choice];
if(choice && ![choiceStr isEqualToString:#""]){
finalWord = [finalWord stringByAppendingString:choiceStr];
break;
}else{
finalWord = [finalWord stringByAppendingString:[NSString stringWithUTF8String:symbol]];
}
} while(ci->Next());
delete ci;
}
}
delete[] symbol;
} while((ri->Next(tesseract::RIL_SYMBOL)));
}
return finalWord;
}
NSInteger intSort(id num1, id num2, void *context) {
NSString *n1 = (NSString *) num1;
NSString *n2 = (NSString *) num2;
n1 = [[n1 componentsSeparatedByString:#"."] objectAtIndex:0];
n2 = [[n2 componentsSeparatedByString:#"."] objectAtIndex:0];
if ([n1 floatValue] > [n2 floatValue]) {
return NSOrderedAscending;
}
else if ([n1 floatValue] < [n2 floatValue]) {
return NSOrderedDescending;
}
return NSOrderedSame;
}
NSInteger intSortDesc(id num1, id num2, void *context) {
NSString *n1 = (NSString *) num1;
NSString *n2 = (NSString *) num2;
n1 = [[n1 componentsSeparatedByString:#"."] objectAtIndex:0];
n2 = [[n2 componentsSeparatedByString:#"."] objectAtIndex:0];
if ([n1 floatValue] < [n2 floatValue]) {
return NSOrderedAscending;
}
else if ([n1 floatValue] > [n2 floatValue]) {
return NSOrderedDescending;
}
return NSOrderedSame;
}
#end

How do I send an array of integers via GKSession bluetooth

I have a problem with sending an array of integers via GKSession.
This is how I did it:
To send it.
-(void)sendData {
NSMutableArray *myArray = [[NSMutableArray alloc] init];
[myArray addObject:[NSNumber numberWithInteger:snakeHead.position.x]];
[myArray addObject:[NSNumber numberWithInteger:snakeHead.position.y]];
[myArray addObject:[NSNumber numberWithInteger:direction.x]];
[myArray addObject:[NSNumber numberWithInteger:direction.y]];
[myArray addObject:[NSNumber numberWithInteger:bodyOffsetX]];
[myArray addObject:[NSNumber numberWithInteger:bodyOffsetY]];
[myArray addObject:[NSNumber numberWithInteger:amountBodies]];
NSData* encodedArray = [NSKeyedArchiver archivedDataWithRootObject:myArray];
[snakeSession sendData:encodedArray toPeers:snakePeers withDataMode:GKSendDataReliable
error:nil];
[encodedArray release];
}
The sendData function is called from a scheduler.
To receive it.
-(void)receiveData:(NSData *)data fromPeer:(NSString *)peer inSession:(GKSession *)session
context:(void *)context {
NSArray *hisArray = [NSKeyedUnarchiver unarchiveObjectWithData:data];
snakeHead2.position = ccp([[hisArray objectAtIndex:0] integerValue],
[[hisArray objectAtIndex:1] integerValue]);
direction2 = ccp([[hisArray objectAtIndex:2] integerValue],
[[hisArray objectAtIndex:3] integerValue]);
bodyOffsetX2 = [[hisArray objectAtIndex:4] integerValue];
bodyOffsetY2 = [[hisArray objectAtIndex:5] integerValue];
amountBodies2 = [[hisArray objectAtIndex:6] integerValue];
}
This does not work and the game crashes.
So what am I doing wrong here?
heres what I would do. it even sends less bytes! (faster)
// to send
int snakeHead_position_x = 0;
int snakeHead_position_y = 0;
int direction_x = 0;
int direction_y = 0;
int bodyOffsetX = 0;
int bodyOffsetY = 0;
int amountBodies = 0;
NSString *package = [NSString stringWithFormat:#"%i|%i|%i|%i|%i|%i|%i",
snakeHead_position_x, snakeHead_position_y, direction_x,
direction_y, bodyOffsetX, bodyOffsetY, amountBodies];
NSData *data = [package dataUsingEncoding:NSASCIIStringEncoding];
assert(data); // this is critical don't remove!
//printf("sending %u bytes...\n", data.length);
[snakeSession sendData:data toPeers:snakePeers withDataMode:GKSendDataReliable error:nil];
// to retrieve
NSArray *intArray = [[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] componentsSeparatedByString:#"|"];
int snakeHead_position_x = [intArray[0] intValue];
int snakeHead_position_y = [intArray[1] intValue];
int direction_x = [intArray[2] intValue];
int direction_y = [intArray[3] intValue];
int bodyOffsetX = [intArray[4] intValue];
int bodyOffsetY = [intArray[5] intValue];
int amountBodies = [intArray[6] intValue];

Resources