How to ignore #2x images - iphone

I have the following code below to populate an array with images:
NSString *fileName;
myArray = [[NSMutableArray alloc] init];
for(int i = 1; i < 285; i++) {
fileName = [NSString stringWithFormat:#"Animation HD1.2 png sequence/HD1.2_%d.png", i];
[myArray addObject:[UIImage imageNamed:fileName]];
NSLog(#"Loaded image: %d", i);
}
In my resources folder i have #2x versions of each of these images. Is there a way (programmatically) that I can ignore the #2x images on retina devices and populate the array with the non-#2x images?
EDIT 1:
I've edited my code to use NSData:
myArray = [[NSMutableArray alloc] init];
for(int i = 1; i < 285; i++) {
fileName = [NSString stringWithFormat:#"Animation HD1.2 png sequence/HD1.2_%d.png", i];
NSData *fileData = [NSData dataWithContentsOfFile:fileName];
UIImage *regularImage = [UIImage imageWithData:fileData];
[myArray addObject:regularImage];
}
falling.animationImages = MYArray;
This is crashing my app with the error: *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil'. Am i using the NSData object wrong?

I believe the question amounts to "How do I bypass the automatic #2x image loading?"
You need to take a path it can't follow. You could pass the contents of each file using NSData dataWithContentsOfFile:options:error: to UIImage imageWithData: This way, imageWithData won't know where the data came from, let alone that there's a 2x version.

I think the NSData technique should work, but you need to get the path from your bundle, you can't just give the filename as a string like that.
Try:
filename = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:#"Animation HD1.2 png sequence/HD1.2_%d.png", i] ofType:nil];

Try this...
//This string will have #"#2x.png"
NSString *verificationString = [myString substringFromIndex:[myString length] - 7];
if(![verificationString isEqualToString:#"#2x.png"])
{
//NOT EQUAL...
}

Related

CHCSV Error : unable to allocate memory for length

I want to parse a .csv file. For this I use the CHCSV Parser. But when I push into the view where the parser should start parsing, the app crashes.
Terminating app due to uncaught exception 'NSMallocException', reason:
'* -[NSConcreteMutableData appendBytes:length:]: unable to allocate
memory for length (4294967295)'
NSString *filePath = #"http://somewhere.com/test.csv";
NSString *fileContent = [NSString stringWithContentsOfURL:[NSURL URLWithString:filePath] encoding:NSUTF8StringEncoding error:nil];
self.csvParser = [[CHCSVParser alloc] initWithContentsOfCSVFile:fileContent];
Edit:
I'm developing for iOS 6+. Thanks for the great comments and answers. I hope to get the right solution.
Input Stream
It doesn't work. When I want to work with the input stream the app crashes because of the wrong encoding.
Incompatible integer to pointer conversion sending 'int' to
parameter of type 'NSStringEncoding *' (aka 'unsigned int *')
NSData *downloadData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://example.com/test.csv"]];
NSInputStream *stream = [NSInputStream inputStreamWithData:downloadData];
self.csvParser = [[CHCSVParser alloc] initWithInputStream:stream usedEncoding:NSUTF8StringEncoding delimiter:#";"];
self.csvParser.delegate = self;
[self.csvParser parse];
CSV-String
NSString *filePath = #"http://example.com/test.csv";
NSString *fileContent = [NSString stringWithContentsOfURL:[NSURL URLWithString:filePath] encoding:NSUTF8StringEncoding error:nil];
self.csvParser = [[CHCSVParser alloc] initWithCSVString:fileContent];
self.csvParser.delegate = self;
[self.csvParser parse];
This parse only (null).
Final Edit: Dave, the author of CHCSVParser, updated his code on github, so this problem should be solved when you use the most recent version. Get it now!
Okay, here we go:
First add the following code in CHCSVParser.m:
In method - (void)_sniffEncoding at the very beginning you have:
uint8_t bytes[CHUNK_SIZE];
NSUInteger readLength = [_stream read:bytes maxLength:CHUNK_SIZE];
[_stringBuffer appendBytes:bytes length:readLength];
[self setTotalBytesRead:[self totalBytesRead] + readLength];
change it to:
uint8_t bytes[CHUNK_SIZE];
NSUInteger readLength = [_stream read:bytes maxLength:CHUNK_SIZE];
if (readLength > CHUNK_SIZE) {
readLength = CHUNK_SIZE;
}
[_stringBuffer appendBytes:bytes length:readLength];
[self setTotalBytesRead:[self totalBytesRead] + readLength];
After that changed I got only null values so I changed the file path (in the sample project it is located in the main(), however I did the parsing in viewDidLoad.
Make sure you copied the file in your bundle directory for that to work!
file = [NSBundle pathForResource:#"Test" ofType:#"scsv" inDirectory:[[NSBundle mainBundle] bundlePath]];
Edit:
When you say you need to download the file you can do following (but notice that this is quick and dirty solution especially on mobile devices)
NSData *downloadData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://www.yourdomain.tld/Test.scsv"]];
NSInputStream *stream = [NSInputStream inputStreamWithData:downloadData];
The last line is the important one here you need to change.
Hope that solves your issue.
Edit 2:
I've just created a repository with a demo project for you where the code actually works. Perhaps you can find out what you do wrong (or at least different). Here is the link.
Edit 3:
Change
self.csvParser = [[CHCSVParser alloc] initWithInputStream:stream usedEncoding:NSUTF8StringEncoding delimiter:#";"];
to
self.csvParser = [[CHCSVParser alloc] initWithInputStream:stream usedEncoding:&encoding delimiter:';'];

Corrupted Images in document directory

I am fetching URL of the images from the server and converting this images into png format using:
NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(img)];
[data1 writeToFile:pngFilePath atomically:YES];
but some of the images are corrupted when i check them after completing the process on simulator.
Hence these images are not displaying on the app wherever needed.
Please see the attached image as some images are corrupted.
Update
I am calling a method in a loop which fetches the images from the server parallel and didFinishLoading I am performing this:
UIImage *img = [UIImage imageWithData:self.data];
NSArray *split = [self.strImageName componentsSeparatedByString:#"/"];
int arrCount=[split count];
NSString *imageName=[split objectAtIndex:arrCount-1];
NSString *docDirec = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *pngFilePath=nil
pngFilePath = [NSString stringWithFormat:#"%#/Thumbs/%#",docDirec,imageName];
NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(img)];
[data1 writeToFile:pngFilePath atomically:YES];
[self.data release]; //don't need this any more, its in the UIImageView now
self.data=nil;
i have the similar problem
i solved it using the below code
- (void)viewWillDisappear:(BOOL)animated
{
if (self.m_objWebManager != nil)//Webmanager is class for downloading the images as a background thread
{
[self.m_objWebManager cancelCommunication];
[self.m_objWebManager release];
self.m_objWebManager = nil;
}
}

From PHP to iPhone table

I have a file named numbers.php on my ftp with the following content:
1/Brian/Red
2/Simon/Blue
3/Louise/Red
How do I get that into a table?
I need the table to show:
Brian
Simon
Loiuse
in the cells and then when you click on one of the names it takes you to a page with the colour matching the name.
I use this code when I just need to read a single line in a php file and output to textfields:
NSString *queryString = [NSString stringWithFormat: #"http://website.com/numbers.php"];
NSData *dataRequest = [NSData dataWithContentsOfURL: [ NSURL URLWithString: queryString]];
NSString *serverOutput = [[[NSString alloc] initWithData:dataRequest encoding: NSASCIIStringEncoding] autorelease];
urlTextField.text = serverOutput;
NSArray *splitString = [serverOutput componentsSeparatedByString: #"/"];
NSString *idOut = [splitString objectAtIndex: 0]; NSString *nameOut = [splitString objectAtIndex: 1]; NSString *colorOut = [splitString objectAtIndex: 2];
idTextField.text = idOut; nameTextField.text = nameOut; colorTextField.text = colorOut;
But I am a bit in doubt when it comes to multiple lines and how to get them into my table view. I assume I need to put the lines into an array?
First, I generate plist-Data on the server with the free avaliable CFPropertyList. Why, because it is verry easy to import plist-structures later.
In the app you can import data this way:
NSArray * myArray = [NSArray arrayWithContentsOfURL:[NSURL
URLWithString:#"http://url.com/foo.plist"]];
you can use NSMutableArray instead when you modifing myArray.
cheers

Downloading and writing images from an array of urls crashing iPad

I am writing images to the directory of my app using the following code in a separate thread
for (int j =0; j<[sorted count]; j++) {
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[sorted objectAtIndex:j]]];
UIImage *image = [UIImage imageWithData:data];
if (image!=nil) {
NSLog(#"%#",[sorted objectAtIndex:j]);
[images addObject:image];
}
}
and
for (int k=0;k<[images count];k++)
{
NSString *temp = [[sorted objectAtIndex:k]lastPathComponent];
NSString *imagePath = [dataPath stringByAppendingPathComponent:temp];
NSData *data = UIImageJPEGRepresentation([images objectAtIndex:k], 1.0f);
[data writeToFile:imagePath atomically:YES];
}
But a weird thing is last two images are not getting written
I've tried everything but it doesn't seem to work.
Anyone have any idea about this?
Not sure what could be causing your issue, but UIKit is not thread safe, so this could be the cause. You could try and execute your code on the main thread just to troubleshoot it (and check that it is correct), then, if my guess is right, look for a workaround.
In looking for a workaround, possibly performSelector:onMainThread: could help.

How do I enumerate and load resources in an iPhone app?

I'm trying to populate an NSArray with a collection of images in Resources. However, for maximum flexibility, I'm trying to avoid hard-coding the filenames or even how many files there are.
Normally, I'd do something like this example from the sample code at apple:
kNumImages = 5; //or whatever
NSMutableArray *images;
for (i = 1; i <= kNumImages; i++)
{
NSString *imageName = [NSString stringWithFormat:#"image%d.jpg", i];
[images addObject:[UIImage imageNamed:imageName];
}
However, I'm trying to avoid kNumImages entirely. Is there a way to run a regex or something on resources?
Here's a snippet that does just that from my iPhone app
// Load item icons
paths = [[NSBundle mainBundle] pathsForResourcesOfType:#"png" inDirectory:nil];
for (NSString *filename in paths) {
filename = [[filename componentsSeparatedByString:#"/"] lastObject];
if ([filename hasPrefix:#"ItemIcon"]) {
[UIImage imageNamed:filename];
}
}
It loops through all resources that have a png extension, and it the filename begins with "ItemIcon" then it loads into UIImage's built in cache.
If you have them in a specific directory, you will need to specify the indirectory: argument.