print nsmutable array using printer in ios - iphone

I have three nsmutable array in ios. I have to print data as below example using printer , How should i do it?
example:--
0.5 1 10
1 10 11
2 5 22
3 4 6

For example these are arrays :
NSArray *arr = [NSArray arrayWithObjects:#"1",#"2",#"3",#"4",#"5",#"6", nil];
NSArray *arr1 = [NSArray arrayWithObjects:#"17",#"27",#"37",#"47",#"57",#"67", nil];
NSArray *arr2 = [NSArray arrayWithObjects:#"171",#"271",#"371",#"471",#"571",#"671", nil];
Now get all data in NSString
NSMutableString *str = [NSMutableString string];
for (int i=0; i<[arr count]; i++)
{
str = [str stringByAppendingFormat:[NSString stringWithFormat:#"%# %# %#\n",[arr objectAtIndex:i],[arr1 objectAtIndex:i],[arr2 objectAtIndex:i]]];
}
NSLog(#"%#",str);
Use toPdfData method to get NSData to print.
NSData *data = [self toPdfData:str];
Add these method:
- (NSData *) toPdfData :(NSMutableString *)str
{
//calculate size
CGSize stringSize = [str sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:CGSizeMake(320 , 999) lineBreakMode:UILineBreakModeWordWrap];
// Creates a mutable data object for updating with binary data, like a byte array
NSMutableData *pdfData = [NSMutableData data];
// Points the pdf converter to the mutable data object and to the UIView to be converted
UIGraphicsBeginPDFContextToData(pdfData, CGRectMake(0, 0, stringSize.width, stringSize.height), nil);
UIGraphicsBeginPDFPage();
// draws rect to the view and thus this is captured by UIGraphicsBeginPDFContextToData
[str drawInRect:CGRectMake(0, 0, stringSize.width, stringSize.height) withFont:[UIFont systemFontOfSize:15]];
// remove PDF rendering context
UIGraphicsEndPDFContext();
// Retrieves the document directories from the iOS device
NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString* documentDirectory = [documentDirectories objectAtIndex:0];
NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:aFilename];
// instructs the mutable data object to write its context to a file on disk
[pdfData writeToFile:documentDirectoryFilename atomically:YES];
NSLog(#"documentDirectoryFileName: %#",documentDirectoryFilename);
return pdfData;
}
EDIT : Now you have PDF Data and PDF file also store in NSDocument Directory so print using UIPrintInteractionController

You can use the UIPrintInteractionController for doing this.
Please check the below code:
NSMutableString *stringToPrint = [[NSMutableString alloc] initWithString:#""];
for(int i = 0;i<[array count];i++)
{
[stringToPrint appendFormat:#"%#",[array objectAtIndex:i]];
if(i%2 == 0)
{
[stringToPrint appendFormat:#"\n"];
}
else
{
[stringToPrint appendFormat:#"\t"];
}
}
UIPrintInteractionController *pic = [UIPrintInteractionController sharedPrintController];
UIPrintInfo *printInfo = [UIPrintInfo printInfo];
printInfo.outputType = UIPrintInfoOutputGeneral;
printInfo.jobName = #"Midhun";
pic.printInfo = printInfo;
UISimpleTextPrintFormatter *textFormatter = [[UISimpleTextPrintFormatter alloc]
initWithText:stringToPrint];
textFormatter.startPage = 0;
textFormatter.contentInsets = UIEdgeInsetsMake(72.0, 72.0, 72.0, 72.0); // 1 inch margins
textFormatter.maximumContentWidth = 6 * 72.0;
pic.printFormatter = textFormatter;
pic.showsPageRange = YES;
void (^completionHandler)(UIPrintInteractionController *, BOOL, NSError *) =
^(UIPrintInteractionController *printController, BOOL completed, NSError *error)
{
if (!completed && error)
{
NSLog(#"Printing could not complete because of error: %#", error);
}
};
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
[pic presentFromBarButtonItem:sender animated:YES completionHandler:completionHandler];
}
else
{
[pic presentAnimated:YES completionHandler:completionHandler];
}
Please read Printing and Drawing in iOS for more details.

Use following code to traverse and print.
for (int i=0; i<[array count]; i++) {
NSLog(#"%#",[array objectAtIndex:i]);
}

Related

Some strange error occurs when manipulating events in the calendar of iOS device

I added some events to the calendar and save their eventIdentifier to file. When i want to remove all my events i read the eventIdentifier from that file to an array and remove each event with its event id. Here is the code to add event to calendar and save their event id to file:
- (void) addEventToCalendar: (id)object
{
#autoreleasepool {
int i = 0;
NSString *string_to_file = #"";
eventStore=[[EKEventStore alloc] init];
for(Schedule *sche in scheduleArray){
EKEvent *addEvent=[EKEvent eventWithEventStore:eventStore];
addEvent.title=sche.course_Name;
addEvent.startDate = [self stringToDate:sche.from_Date];
addEvent.endDate = [self stringToDate:sche.thru_Date];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[addEvent setCalendar:[eventStore defaultCalendarForNewEvents]];
NSDate *date_alarm = [addEvent.startDate dateByAddingTimeInterval:-(10*60)];
addEvent.alarms=[NSArray arrayWithObject:[EKAlarm alarmWithAbsoluteDate:date_alarm]];
NSError *err;
// do save event to calendar
[eventStore saveEvent:addEvent span:EKSpanThisEvent error:&err];
if (err == nil) {
NSString* str = [[NSString alloc] initWithFormat:#"%#", addEvent.eventIdentifier];
string_to_file = [string_to_file stringByAppendingString:str];
string_to_file = [string_to_file stringByAppendingString:#"\n"];
NSLog(#"String %d: %#",i, str);
}
else {
NSLog(#"Error %#",err);
}
i++;
}
// create file to save
[[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
inFile = [NSFileHandle fileHandleForWritingAtPath: filePath];
NSData *data = [string_to_file dataUsingEncoding:NSUTF16StringEncoding];
[inFile writeData:data];
}
}
And the code below to remove all events i have added to calendar
- (void) deleteEventInCalender {
filemgr = [NSFileManager defaultManager];
NSString *filePath = [self getFilePath:#"saveeventid.txt"];
NSFileHandle *inFile;
inFile = [NSFileHandle fileHandleForReadingAtPath:filePath];
NSData *dataFile;
dataFile = [inFile readDataToEndOfFile];
NSString *tmp = #"";
NSString *temp = #"";
tmp = [NSString stringWithCharacters:[dataFile bytes] length:[dataFile length]/sizeof(unichar)];
if(![tmp isEqualToString:#""]){
tmp = [tmp substringFromIndex:1];
event_idArray = [[NSMutableArray alloc] init];
int j = 0;
while (![tmp isEqualToString:#""]){
int index_find_string = [tmp rangeOfString:#"\n"].location;
temp = [tmp substringWithRange:NSMakeRange(0, index_find_string)];
[event_idArray addObject:temp];
tmp = [tmp substringFromIndex:index_find_string + 1];
}
EKEventStore* store = [[EKEventStore alloc] init];
j = 0;
for(NSString *eventid in event_idArray){
EKEvent* event2 = [store eventWithIdentifier:eventid];
if (event2 != nil) {
NSLog(#"log: %d log id: %#", j, eventid);
NSError* error = nil;
// remove event
[store removeEvent:event2 span:EKSpanThisEvent error:&error];
}
j++;
}
[filemgr removeItemAtPath:filePath error:nil];
}
}
All codes above work well when i test on the iOS simulator with calendar.sqlitedb. But it makes some strange errors when i run on iPad device 5.0. That is sometime the calendar not remove event or when all events has been remove then after some minutes all events appear again... I don't understand, i don't know why and i very confuse. Does anyone has the same issue with me? Please share your solution!
Added another question: where the calendar database stored in the iOS 5.0 device.

iphone+UIscrollview or to use uitableview to display image in matrix format

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

exc_bad_access when using a async request

Im making a async request but when I try to parse it with this code
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSDictionary *missionsDict = [responseString JSONValue];
/*NSArray *luckyNumbers = [json objectWithString:responseString error:&error];*/
NSLog(#"user Info array is: %#", missionsDict);
// NSDictionary *array = [luckyNumbers1 objectForKey:#"data"];
NSDictionary *missionsData;
missionsData = [missionsDict objectForKey:#"data"];
NSLog(#"missionsData is: %#", missionsData);
NSEnumerator *inner = [missionsData objectEnumerator];
UIScrollView *missionsScroll;
missionsScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
missionsScroll.contentSize = CGSizeMake(320, 1005);
[self.view addSubview:missionsScroll];
id value;
int badgeY1;
int badgeY2;
int badgeY3;
badgeY1 = 121;
badgeY2 = 161;
badgeY3 = 150;
while((value = [inner nextObject])) {
NSLog(#"progress is: %#", [value objectForKey:#"progress"]);
NSLog(#"user Info array is: %#", missionsDict);
NSLog(#"name is: %#",[value objectForKey:#"reward_definitions"]);
NSLog(#"missionsData is: %#", missionsData);
NSDictionary *moreData;
moreData = [value objectForKey:#"reward_definitions"];
NSEnumerator *inner = [moreData objectEnumerator];
id value2;
int badgeX;
badgeX = 10;
while((value2 = [inner nextObject])) {
UIProgressView *progressView;
progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, badgeY3, 372, 9)];
float progressValue;
progressValue = ([[[value objectForKey:#"progress"] objectForKey:#"earned"] floatValue] / [[[value objectForKey:#"progress"] objectForKey:#"possible"] floatValue]);
NSLog(#"progressValue is: %f", progressValue);
[progressView setProgress:progressValue];
[missionsScroll addSubview:progressView];
UILabel *missionName;
missionName = [[UILabel alloc] initWithFrame:CGRectMake(20, badgeY1, 280, 25)];
missionName.backgroundColor = [UIColor clearColor];
missionName.textColor = [UIColor whiteColor];
missionName.font = [UIFont fontWithName:#"Heiti TC" size:23.0];
missionName.text = [value objectForKey:#"name"];
[missionsScroll addSubview:missionName];
NSLog(#"badgeY2 is: %#", badgeY2);
badgesScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, badgeY2, 318, 70)];
badgesScroll.contentSize = CGSizeMake(320, 70);
[missionsScroll addSubview:badgesScroll];
NSLog(#"Image URL is: %#", [value2 objectForKey:#"image_url"]);
NSURL *url1 = [NSURL URLWithString: [NSString stringWithFormat:#"%#", [value2 objectForKey:#"image_url"]]];
NSData *urlData1 = [NSData dataWithContentsOfURL:url1];
UIImage *image1 = [UIImage imageWithData:urlData1];
UIImageView *badge = [[UIImageView alloc] initWithImage:image1];
[badge setFrame:CGRectMake(badgeX, -10, 70, 70)];
[badgesScroll addSubview:badge];
[badge release];
badgeCount = badgeCount+1;
badgeX = badgeX +80;
}
// NSLog(#"reward_definitions is: %#", [missionsData objectForKey:#"id"]);
// NSLog(#"Image URL is: %#", [[value objectForKey:#"reward_definitions"] objectForKey:#"image_url"]);
//if ( [array isKindOfClass:[NSDictionary class]] ) {
badgeY1 = badgeY1 +100;
badgeY2 = badgeY2 +100;
badgeY3 = badgeY3 +100;
missionCount = missionCount+1;
}
for (int b; badgeCount > 4; b = b+1) {
[badgesScroll setContentSize:CGSizeMake(badgesScroll.contentSize.width+80, badgesScroll.contentSize.height)];
}
for (int a; missionCount > 4; a = a+1) {
missionsScroll.contentSize = CGSizeMake(776, missionsScroll.contentSize.height+200);
}
}
It crashes because of EXC_BAD_ACCESS on NSLog(#"badgeY2 is: %#", badgeY2);
your badgeY2 contains an integer value. To print the integer value with NSLog, you must use %d
You should always keep it in mind while using NSLog, what kind of value it returns!
NSLog(#"badgeY2 is: %d", badgeY2);
There is another heck solution to just let you know
NSLog(#"%#", [NSNumber numberWithInt:badgeY2]);
These are the NSLog format specifiers :
%# Object
%d, %i signed int
%u unsigned int
%f float/double
%x, %X hexadecimal int
%o octal int
%zu size_t
%p pointer
Should be
NSLog(#"badgeY2 is: %i", badgeY2);
badgeY2 is an int, so you must use %i instead of %#

iPhone JSON - Iterate NSArray and get values

I've been trying to solve this myself (I was awake all last night banging my head against a wall) but hopefully someone here can help me.
I have used this tutorial to connect to my JSON datasource (http://www.mobileorchard.com/tutorial-json-over-http-on-the-iphone/) and it works fine but I would now like to get the values (by object key I think).
My json data is as follows:
[{"Id":"1","Name":"Richard","NameOfFile":"1.jpg"},{"Id":"395","Name":"Alex","NameOfFile":"390.jpg"}]
And the code i'm using to connect to it is as follows.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
SBJSON *json = [[SBJSON new] autorelease];
NSArray *myArray = [json objectWithString:responseString error:nil];
[responseString release];
for (int i = 0; i < [myArray count]; i++)
{
for(int colIndex = 0; colIndex < 5; colIndex++)
{
UIImage * myimage = [UIImage imageWithData: [NSData dataWithContentsOfURL: [NSURL URLWithString: #"http://www.goweruk.com/Images/Uploaded/220/873.jpg"]]];
UIImageView *myimageview = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f,50.0f, 50.0f)];
[myimageview setImage:myimage];
CGRect frameRect = myimageview.frame;
frameRect.origin.x = (frameRect.size.width + 14) * colIndex;
frameRect.origin.y = (frameRect.size.height + 14) * i;
myimageview.frame = frameRect;
[self.view addSubview:myimageview];
[myimageview release];
}
}
}
So what i'd like to do is inside that loop, get an item value. Does anyone know how I would do that?
That NSArray is an array of NSDictionary objects, so you will first need to get the dictionary at the desired index using objectAtIndex:, then iterate through the dictionary using for..in:
for (int i = 0; i < [myArray count]; i++)
{
NSDictionary *dict = [myArray objectAtIndex:i];
for(NSString *key in dict) {
//do something with key or [dict objectForKey:key];
}
}

Find out when all processes in (void) is done?

I need to know how you can find out when all processes (loaded) from a - (void) are done, if it's possible.
Why? I'm loading in data for a UITableView, and I need to know when a Loading... view can be replaced with the UITableView, and when I can start creating the cells.
This is my code:
- (void) reloadData {
NSAutoreleasePool *releasePool = [[NSAutoreleasePool alloc] init];
NSLog(#"Reloading data.");
NSURL *urlPosts = [NSURL URLWithString:[NSString stringWithFormat:#"%#", URL]];
NSError *lookupError = nil;
NSString *data = [[NSString alloc] initWithContentsOfURL:urlPosts encoding:NSUTF8StringEncoding error:&lookupError];
postsData = [data componentsSeparatedByString:#"~"];
[data release], data = nil;
urlPosts = nil;
self.numberOfPosts = [[postsData objectAtIndex:0] intValue];
self.postsArrayID = [[postsData objectAtIndex:1] componentsSeparatedByString:#"#"];
self.postsArrayDate = [[postsData objectAtIndex:2] componentsSeparatedByString:#"#"];
self.postsArrayTitle = [[postsData objectAtIndex:3] componentsSeparatedByString:#"#"];
self.postsArrayComments = [[postsData objectAtIndex:4] componentsSeparatedByString:#"#"];
self.postsArrayImgSrc = [[postsData objectAtIndex:5] componentsSeparatedByString:#"#"];
NSMutableArray *writeToPlist = [NSMutableArray array];
NSMutableArray *writeToNoImagePlist = [NSMutableArray array];
NSMutableArray *imagesStored = [NSMutableArray arrayWithContentsOfFile:[rootPath stringByAppendingPathComponent:#"imagesStored.plist"]];
int loop = 0;
for (NSString *postID in postsArrayID) {
if ([imagesStored containsObject:[NSString stringWithFormat:#"%#.png", postID]]){
NSLog(#"Allready stored, jump to next. ID: %#", postID);
continue;
}
NSLog(#"%#.png", postID);
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[postsArrayImgSrc objectAtIndex:loop]]];
// If image contains anything, set cellImage to image. If image is empty, try one more time or use noImage.png, set in IB
if (imageData == nil){
NSLog(#"imageData is empty before trying .jpeg");
// If image == nil, try to replace .jpg with .jpeg, and if that worked, set cellImage to that image. If that is also nil, use noImage.png, set in IB.
imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[[postsArrayImgSrc objectAtIndex:loop] stringByReplacingOccurrencesOfString:#".jpg" withString:#".jpeg"]]];
}
if (imageData != nil){
NSLog(#"imageData is NOT empty when creating file");
[fileManager createFileAtPath:[rootPath stringByAppendingPathComponent:[NSString stringWithFormat:#"images/%#.png", postID]] contents:imageData attributes:nil];
[writeToPlist addObject:[NSString stringWithFormat:#"%#.png", postID]];
} else {
[writeToNoImagePlist addObject:[NSString stringWithFormat:#"%#", postID]];
}
imageData = nil;
loop++;
NSLog(#"imagePlist: %#\nnoImagePlist: %#", writeToPlist, writeToNoImagePlist);
}
NSMutableArray *writeToAllPlist = [NSMutableArray arrayWithArray:writeToPlist];
[writeToPlist addObjectsFromArray:[NSArray arrayWithContentsOfFile:nowPlist]];
[writeToAllPlist addObjectsFromArray:[NSArray arrayWithContentsOfFile:[rootPath stringByAppendingPathComponent:#"imagesStored.plist"]]];
[writeToNoImagePlist addObjectsFromArray:[NSArray arrayWithContentsOfFile:[rootPath stringByAppendingPathComponent:#"noImage.plist"]]];
[writeToPlist writeToFile:nowPlist atomically:YES];
[writeToAllPlist writeToFile:[rootPath stringByAppendingPathComponent:#"imagesStored.plist"] atomically:YES];
[writeToNoImagePlist writeToFile:[rootPath stringByAppendingPathComponent:#"noImage.plist"] atomically:YES];
[releasePool release];
}
It is as simple as returning a bool at the bottom of the selector being run in the background, and reaload the UITableView.
Thanks to #iWasRobbed:
I have never done this, but just speculating: have you tried returning a BOOL at the very end so that the reloadData function will return TRUE when it gets to that point? I am assuming (possibly incorrectly) that the device serially handles tasks one-at-a-time, so give it a shot.