I'm developing a game where there are 4 buildings and in these buildings, there are 3 stages inside. The player can play the stages one by one, from one building to another, however, when they have finished one cycle (eg. going from building 1 stage 1 to building 4 stage 3) I keep getting this error where it's an error 14 (SQLITE_CANTOPEN) whenever the player clicks on another building. It keeps happening every single time I test the app. Can anyone help me? :S
edit: sorry, here's the code I used to open the window to access the game:
NSArray *bldgLevels = [[SQLiteManager sharedManager] fetchDataFromDatabase: MAIN_DATABASE
withQuery: SQL_STMT_GET_BUILDING_LEVELS
withValuesAndTypes: [NSArray arrayWithObjects:
[NSString stringWithFormat: #"%d", gameStateProxy.selectedArea], #"i", nil]];
NSLog(#"bldgLevels: %#", bldgLevels);
NSLog(#"getting player levels");
NSArray *playerLevels = [[SQLiteManager sharedManager] fetchDataFromDatabase: MAIN_DATABASE
withQuery: SQL_STMT_GET_PLAYER_UNLOCKED_LEVELS
withValuesAndTypes: [NSArray arrayWithObjects:
[NSString stringWithFormat: #"%d", gameStateProxy.playerId], #"i", nil]];
NSLog(#"playerLevels: %#", playerLevels);
int i = 0;
while (i < [bldgLevels count])
{
NSDictionary *bldgLevel = (NSDictionary *)[bldgLevels objectAtIndex: i];
int levelId = [(NSNumber *)[bldgLevel objectForKey: #"level_id"] intValue];
int indexOrder = [(NSNumber *)[bldgLevel objectForKey: #"index_order"] intValue];
data = [BldgLevelData createObject];
data.levelId = levelId;
data.levelName = (NSString *)[bldgLevel objectForKey: #"name"];
data.rescuedPtsRequired = [(NSNumber *)[bldgLevel objectForKey: #"rescued_required"] intValue];
data.minPtsToComplete = [(NSNumber *)[bldgLevel objectForKey: #"min_pts"] intValue];
data.lastPlayed = #"";
data.dateAdded = #"";
data.isNew = NO;
data.isCompleted = NO;
data.isLocked = YES;
// Group levels together by their index order
if (indexOrder == 1) { groupId++; }
data.groupId = groupId;
data.indexOrder = indexOrder;
int j = 0;
while (j < [playerLevels count])
{
NSDictionary *playerLevel = (NSDictionary *)[playerLevels objectAtIndex: j];
int playerLevelId = [(NSNumber *)[playerLevel objectForKey: #"level_id"] intValue];
if (levelId == playerLevelId)
{
data.rescuedHighScore = [(NSNumber *)[playerLevel objectForKey: #"rescued_highscore"] intValue];
data.rescuedScore = [(NSNumber *)[playerLevel objectForKey: #"rescued_score"] intValue];
data.lastPlayed = (NSString *)[playerLevel objectForKey: #"lastplayed"];
data.dateAdded = (NSString *)[playerLevel objectForKey: #"dateadded"];
data.isNew = ([(NSString *)[playerLevel objectForKey: #"lastplayed"] isEqualToString: #""]);
data.isCompleted = ([(NSNumber *)[playerLevel objectForKey: #"completed"] intValue] == 1);
data.isLocked = NO;
break;
}
j++;
}
if (indexOrder == 1)
{
list = [NSMutableArray arrayWithCapacity: 1];
groupData = [BldgLevelGroupData createObject];
groupData.groupId = groupId;
groupData.firstLevelId = levelId;
groupData.timeLimit = [(NSNumber *)[bldgLevel objectForKey: #"time_limit"] intValue];
groupData.list = list;
// Get SOS items
NSMutableArray *sosItems = [NSMutableArray arrayWithCapacity: 0];
//
NSLog(#"getting levelSOSItems");
NSLog(#"i: %d, j: %d", i, j);
NSLog(#"list: %#", list);
NSLog(#"levelId: %d", levelId);
NSArray *levelSOSItems = [[SQLiteManager sharedManager] fetchDataFromDatabase: MAIN_DATABASE
withQuery: SQL_STMT_GET_LEVEL_SOS
withValuesAndTypes: [NSArray arrayWithObjects:
[NSString stringWithFormat: #"%d", levelId], #"i", nil]];
NSLog(#"Levelsositems: %#", levelSOSItems);
NSLog(#"getting player sos Items");
NSArray *playerSOSItems = [[SQLiteManager sharedManager] fetchDataFromDatabase: MAIN_DATABASE
withQuery: SQL_STMT_GET_PLAYER_SOS
withValuesAndTypes: [NSArray arrayWithObjects:
[NSString stringWithFormat: #"%d", gameStateProxy.playerId], #"i",
nil]];
NSLog(#"playerSoSItems: %#", playerSOSItems);
j = 0;
while (j < [levelSOSItems count])
{
SOSItemData *sosItemData = [SOSItemData createObject];
sosItemData.itemId = [(NSNumber *)[(NSDictionary *)[levelSOSItems objectAtIndex: j] objectForKey: #"sos_id"] intValue];
sosItemData.itemName = (NSString *)[(NSDictionary *)[levelSOSItems objectAtIndex: j] objectForKey: #"name"];
sosItemData.desc = (NSString *)[(NSDictionary *)[levelSOSItems objectAtIndex: j] objectForKey: #"desc"];
sosItemData.coins = [(NSNumber *)[(NSDictionary *)[levelSOSItems objectAtIndex: j] objectForKey: #"coins_cost"] intValue];
sosItemData.cash = [(NSNumber *)[(NSDictionary *)[levelSOSItems objectAtIndex: j] objectForKey: #"cash_cost"] intValue];
sosItemData.rescuedPtsRequired = [(NSNumber *)[(NSDictionary *)[levelSOSItems objectAtIndex: j] objectForKey: #"rescued_required"] intValue];
int k = 0;
while (k < [playerSOSItems count])
{
if ([(NSNumber *)[(NSDictionary *)[playerSOSItems objectAtIndex: k] objectForKey: #"sos_id"] intValue] == sosItemData.itemId)
{
sosItemData.qty = [(NSNumber *)[(NSDictionary *)[playerSOSItems objectAtIndex: k] objectForKey: #"qty"] intValue];
break;
}
k++;
}
//NSLog(#"%#", sosItemData);
[sosItems addObject: sosItemData];
j++;
}
groupData.sosItems = sosItems;
[groupsList addObject: groupData];
}
NSLog(#"%#", data);
[list addObject: data];
i++;
}
and here's the code I used to fetch the data from the database:
-(NSArray *) fetchDataFromDatabase:(NSString *)dbPath withQuery: (NSString *)sql withValuesAndTypes: (NSArray *)params
{
/*
dbPath - Name of database file
sql - SQL statement. Prepared statements are allowed to be used here (refer to params
params - Array containing data and its corresponding data type
*/
NSMutableArray *result = nil;
//make sure db is closed
NSLog(#"close database first!");
sqlite3_close(database);
NSLog(#"open database!");
int dbStatus = [self openDatabase: dbPath];
if (dbStatus == SQLITE_OK)
{
//int stmtStatus = sqlite3_prepare_v2(database, [sql UTF8String], -1, &stmt, NULL);
int stmtStatus = [self prepareStatement: sql withParams: params];
if(stmtStatus == SQLITE_OK)
{
result = [NSMutableArray arrayWithCapacity: 1];
while(sqlite3_step(stmt) == SQLITE_ROW)
{
NSMutableDictionary *row = [NSMutableDictionary dictionaryWithCapacity: 1];
int columnCount = sqlite3_column_count(stmt);
int j = 0;
while (j < columnCount)
{
/*
Possible sqlite data types:
SQLITE_INTEGER, SQLITE_FLOAT, SQLITE_TEXT, SQLITE_BLOB, SQLITE_NULL
*/
if (sqlite3_column_type(stmt, j) == SQLITE_INTEGER)
{
[row setObject: [NSNumber numberWithInt: sqlite3_column_int(stmt, j)]
forKey: [NSString stringWithUTF8String: sqlite3_column_name(stmt, j)]];
}
else if (sqlite3_column_type(stmt, j) == SQLITE_FLOAT)
{
[row setObject: [NSNumber numberWithDouble: sqlite3_column_double(stmt, j)]
forKey: [NSString stringWithUTF8String: sqlite3_column_name(stmt, j)]];
}
else if (sqlite3_column_type(stmt, j) == SQLITE_TEXT)
{
[row setObject: [NSString stringWithFormat: #"%s", sqlite3_column_text(stmt, j)]
forKey: [NSString stringWithUTF8String: sqlite3_column_name(stmt, j)]];
}
else if (sqlite3_column_type(stmt, j) == SQLITE_NULL)
{
[row setObject: [NSNull null]
forKey: [NSString stringWithUTF8String: sqlite3_column_name(stmt, j)]];
}
j++;
}
[result addObject: row];
}
}
else { NSLog(#"stmt error: %d", stmtStatus); }
}
else if (dbStatus == 14)
{
NSLog(#"db error: %d", dbStatus);
NSLog(#"killing app.");
exit(0);
}
else { NSLog(#"db error: %d", dbStatus); }
//Even though the open call failed, close the database connection to release all the memory.
sqlite3_close(database);
return result;
}
sorry if it is wrong..... in your code you didn't finalize statement but useed stmt variable .before close DB ,we should finalize statement if we use statement.....
comment for finalize statement
sqlite3_finalize(Stmt);
Related
This question already has answers here:
How would I combine two arrays in Objective-C?
(2 answers)
Closed 9 years ago.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *error;
json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(#"json.... %#",json);
id jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:nil];
NSLog(#"jsonObject=%#", jsonObject);
NSDictionary *checkArray=[json valueForKey:#"ND"];
NSArray *tel = [checkArray valueForKey:#"FN"];
testArray = [[NSMutableArray alloc]init];
testArray1 = [[NSMutableArray alloc]init];
newsarray = [[NSMutableArray alloc]init];
for (id photo in tel)
{
if (photo == [NSNull null])
{
NSString *test8;
test8 = #"empty";
[testArray addObject:test8];
}
else
{
// photo isn't null. It's an array
NSArray *innerPhotos = photo;
[testArray addObject:photo];
}
}
NSArray *tel1 = [checkArray valueForKey:#"LN"];
for (id photo1 in tel1)
{
if (photo1 == [NSNull null])
{
NSString *test8;
test8 = #"empty";
[testArray1 addObject:test8];
}
else
{
// photo isn't null. It's an array
//NSArray *innerPhotos1 = photo1;
[testArray1 addObject:photo1];
}
}
newsarray = [NSMutableArray arrayWithArray:[testArray arrayByAddingObjectsFromArray:testArray1]];
NSLog(#"testArray =%#",newsarray);
here i want to combine two array values "testArray" and "testArray1"
my mutablearray values are
testArray = aa, bb, cc, dd...
testArray1= xx, yy, zz, ss...
i would like to expect my output like
aa xx, bb yy, cc zz, dd ss
Try this:
for (int i=0;i<[testArray count];i++){
NSString *tmpObject=[NSString stringWithFormat:#"%# %#",
[testArray objectAtIndex:i],
[testArray1 objectAtIndex:i]];
[newArray addObject tmpObject];
tmpObject=nil;
}
you can do something like below..
NSMutableArray *aryFinal=[[NSMutableArray alloc]init];
int count = [testArray count]+[testArray1 count];
for(int i=0;i<count;i++)
{
if(i%2==0)
[aryFinal addobject:[testArray objectAtIndex:i]];
else
[aryFinal addobject:[testArray1 objectAtIndex:i]];
}
let me know it is working or not!!!
NSMutableArray *array1 = [NSMutableArray arrayWithObjects:#"AA",#"BB",#"CC" nil];
NSArray *array2 = [NSArray arrayWithObjects:#"XX",#"YY",#"ZZ" nil];
for (int i=0; i<[array1 count];i++)
[array1 replaceObjectAtIndex:i
withObject:[NSString stringWithFormat:#"%# %#",
array1[i],
array2[i]]];
NSLog(#"%#",array1);
Output:
"AA XX","BB YY","CC ZZ"
To simply add two arrays:
[testArray setArray: testArray1];
But if you want desired result:
NSMutableArray *arrFinal=[[NSMutableArray alloc]init];
for(int i = 0; i < (testArray.count + testArray1.count); i++)
{
if(i%2 == 0)
[arrFinal addobject:[testArray objectAtIndex:i]];
else
[arrFinal addobject:[testArray1 objectAtIndex:i]];
}
Do not need to go for third array. You can use replaceObjectAtIndex method of NSMutableArray.
This way..
NSMutableArray *array1 = [NSMutableArray arrayWithObjects:#"aa",#"bb", nil];
NSArray *array2 = [NSArray arrayWithObjects:#"xx",#"yy", nil];
for (int i=0; i<[array1 count];i++)
[array1 replaceObjectAtIndex:i withObject:[NSString stringWithFormat:#"%# %#",array1[i],array2[i]]];
for aa xx, bb yy, cc zz, dd ss output:
int i=-1;
for(int k =0;k<[testArray1 count];++k)
{
i=i+2;
[testArray insertObject:[testArray1 objectAtIndex:k] atIndex:i];
}
NSMutableArray *array1,*array2;
//////array1 and array2 initialise it with your values
NSMutableArray *finalArray = [[NSMutableArray alloc]init]
int totalcount = 0;
if (array1.count > array2.count) {
totalcount = array1.count;
}
else
totalcount = array2.count;
for (int i = 0; i<totalcount; i++) {
if (i <= array1.count-1) {
[finalArray addObject:[array1 objectAtIndex:i]];
}
if (i <= array2.count-1) {
[finalArray addObject:[array2 objectAtIndex:i]];
}
}
I have Plist with list with List of Dictionaries(item0,item1,item2)..
generally when I display in screen ..it populates in ascending order...item0 then item1 then item2......and so on..I want the Plist to be display in reverse order as itemn,itemn-1.........item2,item1,item0
.
and this is how code goes...and How Can I reverse it ..need changes in Array below
NSMutableArray *Array=[NSMutableArray arrayWithArray:[self readFromPlist]];
NSMutableArray *items = [[NSMutableArray alloc] init];
for (int i = 0; i< [Array count]; i++)
//how to reverse by making changes here
//for (int i =[Array count] ; i>0; i--) does not work
{
id object = [Array objectAtIndex:i];
if ([object isKindOfClass:[NSDictionary class]])
{
NSDictionary *objDict = (NSDictionary *)object;
tempItemi =[[ECGraphItem alloc]init];
NSString *str=[objDict objectForKey:#"title"];
NSLog(#"str value%#",str);
float f=[str floatValue];
//my code here
}
Use reverse enumeration
for (id someObject in [myArray reverseObjectEnumerator]){
// print some info
NSLog([someObject description]);
}
For your code:
for (id object in [Array reverseObjectEnumerator]){
if ([object isKindOfClass:[NSDictionary class]])
{
NSDictionary *objDict = (NSDictionary *)object;
tempItemi =[[ECGraphItem alloc]init];
NSString *str=[objDict objectForKey:#"title"];
NSLog(#"str value%#",str);
float f=[str floatValue];
//my code here
}
}
Also in your code:
//for (int i =[Array count] ; i>0; i--) does not work
should be as
for (int i =[Array count]-1 ; i>=0; i--)
You are itrating from count to 1 whereas array has objects from index count-1 to 0
e.g.
Array with 10 objects has objects from index 0 to 9
for (int i =[Array count]-1 ; i >= 0; i--)
{
id object = [Array objectAtIndex:i];
if ([object isKindOfClass:[NSDictionary class]])
{
NSDictionary *objDict = (NSDictionary *)object;
tempItemi =[[ECGraphItem alloc]init];
NSString *str=[objDict objectForKey:#"title"];
NSLog(#"str value%#",str);
float f=[str floatValue];
//my code here
}
I was looking for some ready code so I could insert my data, labels etc. into a function and receive a ready google-chart like this.
But I didn't find any. Any ideas?
In the mean time, I wrote a function that receive all the necessary parameters, creates a google chart and converts it UIImage. Here it is:
-(UIImage )produceGoogleChartImage:(NSString)title
xAxis:(NSArray*)axisXLabels
yAxis:(NSArray*)axisYLabels
andData:(NSArray*)dataValues
color:(NSString*)lineColor
chartWidth:(NSNumber*)width
chartHight:(NSNumber*)hight
lagendLabel:(NSString*)legend
minScale:(NSNumber*)minScale
maxScale:(NSNumber*)maxScale{
NSMutableString *myurl = [NSMutableString stringWithString:#"http://chart.googleapis.com/chart?chxl=0:|"];
//axisXLabels
int countAxisXLabels = [axisXLabels count];
for(NSUInteger i = 0; i < countAxisXLabels; ++i)
{
NSNumber *value = [axisXLabels objectAtIndex:i];
[myurl appendFormat:#"%#", value];
if(i < countAxisXLabels - 1)
[myurl appendString:#"|"];
}
[myurl appendString:#"|1:|"];
//axisYLabels
int countAxisYLabels = [axisYLabels count];
for(NSUInteger i = 0; i < countAxisYLabels; ++i)
{
NSNumber *value = [axisYLabels objectAtIndex:i];
[myurl appendFormat:#"%#", value];
if(i < countAxisYLabels - 1)
[myurl appendString:#"|"];
}
[myurl appendString:#"&chxr=0,0,105|1,3.333,100&chxt=x,y&chs="];
//size
[myurl appendFormat:#"%#x%#&cht=lc&chd=t:", width,hight];
//dataValues
int countDataValues = [dataValues count];
for(NSUInteger i = 0; i < countDataValues; ++i)
{
NSNumber *value = [dataValues objectAtIndex:i];
[myurl appendFormat:#"%#", value];
if(i < countDataValues - 1)
[myurl appendString:#","];
}
//legend
[myurl appendFormat:#"&chdl=%#&chg=25,50&chls=2&",legend];
//color
[myurl appendFormat:#"chm=o,%#,0,-2,8&chco=%#",lineColor,lineColor];
//title
[myurl appendFormat:#"&chtt=+%#",title];
//scale
[myurl appendFormat:#"&chds=%#,%#",minScale,maxScale];
NSString *theurl=[myurl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:theurl]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSURLResponse* response;
NSError* error;
NSData *imageData=[NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response
error:&error];
NSLog(#"%#",error);
NSLog(#"%#",response);
NSLog(#"%#",imageData);
UIImage *myimage = [[UIImage alloc] initWithData:imageData];
return myimage;
// Chart Wizard: https://developers.google.com/chart/image/docs/chart_wizard
}
And here is the test function:
-(void)test{
NSString* title = #"Height History";
NSArray *axisXLabels = [NSArray arrayWithObjects:
#"Jan",
#"Feb",
#"Mar",
#"Jun",
#"Jul",
#"Aug",
nil];
NSArray *axisYLabels = [NSArray arrayWithObjects:
[NSNumber numberWithInt:0],
[NSNumber numberWithInt:50],
[NSNumber numberWithInt:150],
[NSNumber numberWithInt:200],
nil];
NSArray *dataValues = [NSArray arrayWithObjects:
[NSNumber numberWithInt:130],
[NSNumber numberWithInt:140],
[NSNumber numberWithInt:140],
[NSNumber numberWithInt:150],
[NSNumber numberWithInt:170],
[NSNumber numberWithInt:180],
nil];
NSString *lineColor = #"FF9900";
NSNumber *width = [NSNumber numberWithInt:300];
NSNumber *hight = [NSNumber numberWithInt:200];
NSNumber *minScale = [NSNumber numberWithInt:0];
NSNumber *maxScale = [NSNumber numberWithInt:200];
NSString *legendLabel = #"cm";
UIImage *myimage =[self produceGoogleChartImage:title xAxis:axisXLabels yAxis:axisYLabels andData:dataValues color:lineColor
chartWidth:width chartHight:hight lagendLabel:legendLabel
minScale:minScale maxScale:maxScale];
_chartImage.image=myimage;
}
You should get image, like the one in the question.
I have the following piece of code in displaying the mapview.
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
MKCoordinateRegion region = mapView.region;
MKCoordinateSpan span;
span.latitudeDelta=100;
span.longitudeDelta=100;
NSString *compositeName =(NSString*)ABRecordCopyCompositeName(person);
if([compositeName length] < 1){
firstName = #"No Name";
lastName = #"";
}
else if([firstName length] < 1 && [lastName length] < 1){
firstName = compositeName;
lastName = #"";
}
else if([firstName length] < 1)
{
firstName = lastName;
lastName = #"";
}
addAnnotation = [[[MyAnnotation alloc] initWithCoordinate:mapCenter title:firstName SubTitle:lastName ]autorelease];
[mapView addAnnotation:addAnnotation];
region.span=span;
region.center=mapCenter;
[pool release];
When analysing the project to check for memory leaks, I get the warning, "Potential leak of an object stored into compositeName". Should I release compositeName of type string.
Here object allocated and stored into 'compositeName' has a retain count of +1. I think you just need to release compositeName in this case.
This is Answer similar to my answer
please try below code for get all the information of people from phonebook
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
ABAddressBookRef addressBook = ABAddressBookCreate();
int i;
NSString *strName = #"";
NSString* company = #"";
NSString *address = #"";
NSString *suburb = #"";
NSString *postalcode = #"";
NSString *state = #"";
NSString *country = #"";
NSString *mobile = #"";
NSString *phone = #"";
NSString *emailid = #"";
strName = (NSString *)ABRecordCopyCompositeName((ABRecordRef) person);
CFStringRef name = ABRecordCopyCompositeName((ABRecordRef) person);
company = (NSString *)ABRecordCopyValue((ABRecordRef) person, kABPersonOrganizationProperty);
NSArray* allPeople = (NSArray *)ABAddressBookCopyPeopleWithName(addressBook,name);
CFRelease(name);
for (i = 0; i < [allPeople count]; i++)
{
ABRecordRef record = [allPeople objectAtIndex:i];
ABMutableMultiValueRef multiValue = ABRecordCopyValue(record, kABPersonAddressProperty);
for(CFIndex i=0; i<ABMultiValueGetCount(multiValue); i++)
{
NSString* HomeLabel = (NSString*)ABMultiValueCopyLabelAtIndex(multiValue, i);
if([HomeLabel isEqualToString:#"_$!<Home>!$_"])
{
CFDictionaryRef dict = ABMultiValueCopyValueAtIndex(multiValue, i);
address = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressStreetKey)];
suburb = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressCityKey)];
postalcode = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressZIPKey)];
state = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressStateKey)];
country = [NSString stringWithFormat:#"%#", CFDictionaryGetValue(dict, kABPersonAddressCountryKey)];
CFRelease(dict);
}
CFRelease(HomeLabel);
}
CFRelease(multiValue);
}
CFRelease(allPeople);
ABMultiValueRef phones =(NSString*)ABRecordCopyValue(person, kABPersonPhoneProperty);
NSString* mobileLabel = nil;
for(CFIndex i = 0; i < ABMultiValueGetCount(phones); i++)
{
mobileLabel = (NSString*)ABMultiValueCopyLabelAtIndex(phones, i);
if([mobileLabel isEqualToString:(NSString *)kABPersonPhoneMobileLabel])
{
mobile = (NSString*)ABMultiValueCopyValueAtIndex(phones, i);
NSLog(#"phone %#",mobile);
}
else if ([mobileLabel isEqualToString:(NSString*)kABPersonPhoneIPhoneLabel])
{
phone = (NSString*)ABMultiValueCopyValueAtIndex(phones, i);
NSLog(#"phone %#",phone);
CFRelease(mobileLabel);
break ;
}
CFRelease(mobileLabel);
}
CFStringRef value, label;
ABMutableMultiValueRef multi = ABRecordCopyValue(person, kABPersonEmailProperty);
CFIndex count = ABMultiValueGetCount(multi);
if (count == 1)
{
value = ABMultiValueCopyValueAtIndex(multi, 0);
emailid = (NSString*) value;
NSLog(#"self.emailID %#",emailid);
CFRelease(value);
}
else
{
for (CFIndex i = 0; i < count; i++)
{
label = ABMultiValueCopyLabelAtIndex(multi, i);
value = ABMultiValueCopyValueAtIndex(multi, i);
// check for Work e-mail label
if (CFStringCompare(label, kABWorkLabel, 0) == 0)
{
emailid = (NSString*) value;
NSLog(#"self.emailID %#",emailid);
}
else if(CFStringCompare(label, kABHomeLabel, 0) == 0)
{
emailid = (NSString*) value;
NSLog(#"self.emailID %#",emailid);
}
CFRelease(label);
CFRelease(value);
}
}
CFRelease(multi);
}
CFRelease(phones);
CFRelease(addressBook);
[self dismissModalViewControllerAnimated:YES];
return NO;
}
I want to display the image(which comes from webservice) the format such that the output in the screen appears like below image:-
Now the logic i had implemented is,i had added the image in uiscrollview.
with the below logic:-
for (int j=0;j<9;j++) {
for (int i=0; i<[mainRestaurantArray count];i++) {
if ([[[mainRestaurantArray objectAtIndex:i] valueForKey:#"Image"] isKindOfClass:[UIImage class]]) {
[CombineArray addObject:[mainRestaurantArray objectAtIndex:i]];
//NSLog(#"cnt=>%d array==>%#",cnt,[CombineArray objectAtIndex:cnt]);
UIButton* btn = [[UIButton alloc]init];
btn.tag = cnt;
btn.frame = CGRectMake(15+(cnt%5)*60, 15+(cnt/5)*60,Width,Height);
btn.backgroundColor = [UIColor greenColor];
[btn setBackgroundImage:[[CombineArray objectAtIndex:cnt] valueForKey:#"Image"] forState:UIControlStateNormal];
[btn addTarget:self action:#selector(Buttonclick:) forControlEvents:UIControlEventTouchUpInside];
[ScrlPhotos addSubview:btn];
[btn release];
cnt++;
}
}
[mainRestaurantArray release];
counter++;
[self urlcalled];//The function which calls the webservice
}
//}
ScrlPhotos.contentSize = CGSizeMake(320, ([CombineArray count]/5.0)*60+25);
The function which does the webservice is below:-
-(void)urlcalled{
#try
{
if (rangeDistance == nil) {
rangeDistance =#"100";
}
urlstring[0]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Gym&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[1]=[NSString stringWithFormat:#"http://www.google.com/maps?q=resort&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[2]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Tourist place&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[3]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Hotels&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[4]=[NSString stringWithFormat:#"http://www.google.com/maps?q=shopping Mall&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[5]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Industries&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[6]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Shopping_mall&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[7]=[NSString stringWithFormat:#"http://www.google.com/maps?q=garden&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[8]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Religious Place&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
urlstring[9]=[NSString stringWithFormat:#"http://www.google.com/maps?q=Restaurants&sll=%#,%#&radius=200000&output=json",AppDel.Latitude,AppDel.Longitude];
NSLog(#"conte==>%d urlstring[counter]==>%#",counter,urlstring[counter]);
NSString *str = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlstring[counter]]];
str1 = [str substringFromIndex:9];
//NSLog(#"===>%#",str1);
NSArray *array = [str1 componentsSeparatedByString:#"overlays:"];
NSString *str2 = [array objectAtIndex:1];
NSString *finalUpperStr = [str2 substringFromIndex:21];
array1 = [finalUpperStr componentsSeparatedByString:#"},panel:"];
NSString *strF = [array1 objectAtIndex:0];
NSArray *arrayF = [strF componentsSeparatedByString:#"{id:"];
///////....................this object will change as require in for loop .............................//
mainRestaurantArray = [[NSMutableArray alloc] init];
for (int i=1; i<[arrayF count]-5; i++) {
NSString *strF12 = [arrayF objectAtIndex:i];
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
NSArray *aryF23 = [strF12 componentsSeparatedByString:#"latlng:{"];
//NSLog(#"%#",[aryF23 objectAtIndex:1]);
NSString *strF23 = [aryF23 objectAtIndex:1];
NSArray *ar = [strF23 componentsSeparatedByString:#"},image:"];
//NSLog(#"%#",[ar objectAtIndex:0]);
NSString *strLat = [ar objectAtIndex:0];
NSArray *arrayLat = [strLat componentsSeparatedByString:#","];
NSString *strFLat = [[arrayLat objectAtIndex:0] substringFromIndex:4];
NSString *strLong = [[arrayLat objectAtIndex:1] substringFromIndex:4];
//NSLog(#"Lati = %# Longi = %#" , strFLat , strLong);
[dic setValue:strFLat forKey:#"Latitude"];
[dic setValue:strLong forKey:#"Longitude"];
NSString *strLAdd = [ar objectAtIndex:1];
NSArray *arrayLAdd = [strLAdd componentsSeparatedByString:#"laddr:"];
//NSLog(#"%#",[arrayLAdd objectAtIndex:1]);
NSString *strLAdd1 = [arrayLAdd objectAtIndex:1];
NSArray *arrayLAdd1 = [strLAdd1 componentsSeparatedByString:#"geocode:"];
// NSLog(#"%#",[arrayLAdd1 objectAtIndex:0]);
NSString *strAddres = [[arrayLAdd1 objectAtIndex:0] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
//NSLog(#"%#",strAddres);
[dic setValue:strAddres forKey:#"Address"];
NSString *strName = [arrayLAdd1 objectAtIndex:1];
NSArray *arrayName = [strName componentsSeparatedByString:#"name:"];
NSString *strName1 = [[arrayName objectAtIndex:1]stringByReplacingOccurrencesOfString:#"\"" withString:#""];
NSArray *arrayName1 = [strName1 componentsSeparatedByString:#"infoWindow:"];
[dic setValue:[arrayName1 objectAtIndex:0] forKey:#"Name"];
// for image load .. 07Dec..
NSString *strImage= [arrayF objectAtIndex:i];
NSRange range = [strImage rangeOfString:#"photoUrl"];
if(range.location == NSNotFound){
NSLog(#"Not found");
[dic setValue:#"" forKey:#"Image"];
}else{
NSArray *arrayImage = [strImage componentsSeparatedByString:#"photoUrl:"];
NSString *strImage1 = [arrayImage objectAtIndex:1];
NSArray *arrayImage1 = [strImage1 componentsSeparatedByString:#",photoType:"];
NSString *strfindImage = [[arrayImage1 objectAtIndex:0] stringByReplacingOccurrencesOfString:#"\"" withString:#""];
myImage = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:strfindImage]]];
[dic setValue:myImage forKey:#"Image"];
}
[mainRestaurantArray addObject:dic];
if (i==20) {
break;
}
}
}
#catch (NSException * e)
{
NSLog(#"NSException==>%#",e);
}
}
But the problem i am facing is the image is displayed after completing the loop at 10 times.
I want to display the image parallely as it comes from webservice,so that time taken should be less..
Is there any way out..
Please help me.
Use UIImageView+cacheWeb.. it makes lazy loading a lot easier
http://hackemist.com/SDWebImage/doc/Categories/UIImageView+WebCache.html