I have a text file that I download at launch from my website. It saves it to the Documents directory in the app. I want to read and process that text file and turn it into an NSArray.
I tried this:
- (NSArray *)articleReason {
NSString *filename3 = #"GameList.txt";
NSArray *pathArray3 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString *documentsDirectory3 = [pathArray3 objectAtIndex:0];
NSString *yourSoundPath3 = [documentsDirectory3 stringByAppendingPathComponent:filename3];
NSURL *url = [NSURL fileURLWithPath:yourSoundPath3 isDirectory:NO];
NSString *urlData = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSArray *parsed = [urlData componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
NSIndexSet *indexes = [parsed indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
NSRange range = [(NSString *)obj rangeOfString:#"Reason:"];
if (range.location != NSNotFound)
{
return YES;
}
return NO;
}];
NSArray *disallowed = [parsed objectsAtIndexes:indexes];
NSString * myString = [disallowed componentsJoinedByString:#" "];
disallowed = [myString componentsSeparatedByString:#"Reason: "];
return disallowed;
}
This does not work. The thing is, if I download the text file while making the NSArray, it ends up working. Here's that code:
- (NSArray *)articleReason {
NSString *stringURL = kGameURL;
NSURL *url = [NSURL URLWithString:stringURL];
NSString *urlData = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSArray *parsed = [urlData componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
NSIndexSet *indexes = [parsed indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
NSRange range = [(NSString *)obj rangeOfString:#"Reason:"];
if (range.location != NSNotFound)
{
return YES;
}
return NO;
}];
NSArray *disallowed = [parsed objectsAtIndexes:indexes];
NSString * myString = [disallowed componentsJoinedByString:#" "];
disallowed = [myString componentsSeparatedByString:#"Reason: "];
return disallowed;
}
Any idea why this is not working? I verified in the Documents directory that the text file is downloading correctly. I do the downloading of the file in didFinishLaunching in the App Delegate. Here's that code:
NSString *stringURL2 = kGameURL;
NSURL *url2 = [NSURL URLWithString:stringURL2];
NSString *urlData2 = [NSString stringWithContentsOfURL:url2 encoding:NSUTF8StringEncoding error:nil];
NSFileManager *fileManager2 = [NSFileManager defaultManager];
NSString *docsDirectory2 = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *path2 = [docsDirectory2 stringByAppendingPathComponent:#"GameList.txt"];
[urlData2 writeToFile:path2 atomically:YES ];
Any help would be greatly appreciated.
Figured it out.
[urlData2 writeToFile:path2 atomically:YES ];
Writeto file needed it include the encoding.
Related
I'm having a big trouble. I'd like to concatenate data of multiple textfiles into another textfiles. But I cannot. can you help me ? Many thanks
Read each file one by one,
NSString *firstFileContent = [NSString stringWithContentsOfFile:<your file path>
encoding:NSASCIIStringEncoding
error:nil];
//Similarly read other files, and store them in secondFileContent and thirdFileContent.
//now concatenate all to form one big string.
NSString *bigString = [NSString stringWithFormat:#"-First File- \n%# \n-Second File- \n%#\n-Third File-\n%#",firstFileContent, secondFileContent, thirdFileContent];
//write to file, create a new one
[bigString writeToFile:<path to write>
atomically:YES
encoding:NSASCIIStringEncoding
error:nil];
Edit 1 :
As per your comment that your file is in DocumentDirectory use this code :
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:<your file name>];
NSString *content = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
First load content of file in NSString and use following code:
NSString *strConcatenate = [NSString stringWithFormat:#"%# %# %#", textfiles1, textfiles2, textfiles3];
NSLog(#"%#", strConcatenate);
You just have to load the content of the files into NSMutableString and concatenate them :
NSMutableString *myString = #"Content of the first file";
NSString *test = [myString stringByAppendingString:#" content of the second file"];
You need to read the text files in from the bundle and then append them, once you have that then write it back out. I wrote this example and I hope you can learn from it.
NSMutableString *mutableString = [[NSMutableString alloc] init];
NSArray *textFiles = #[ #"textfile1", #"textfile2", #"textfile3" ];
for (NSString *textFileName in textFiles) {
NSString *path = [[NSBundle mainBundle] pathForResource:textFileName
ofType:#"txt"];
NSError *error = nil;
NSString *content = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:&error];
if (content) {
[mutableString appendFormat:#"%#\n", content];
} else {
NSLog(#"%#", error.localizedDescription);
}
}
NSLog(#"%#", mutableString);
NSError *error = nil;
BOOL result = [mutableString writeToFile:#"concatenated_file.txt" atomically:NO encoding:NSStringEncodingConversionAllowLossy error:&error];
if (!result) {
NSLog(#"%#", error.localizedDescription);
}
I am trying to fetch Images which i am storing in directory which i have shown in below code . I have tried a lot in StachOverFlow And Chats but not able to achieve the task . Actually i want to generate array of images from the array of filePath which are storing the path of images . Which i will show in UICollectionView . Please check my code and tell me what all can be done to achieve the needed . Thanks in advance
I have array of filepath already generated , i just want to fetch images from them and show it in grid view
-(void)plistRender{
// get paths from root direcory
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
// get documents path
NSString *documentsPath = [paths objectAtIndex:0];
// get the path to our Data/plist file
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"PhotoBucket.plist"];
//pngDATA.....
NSString *totalName = [NSString stringWithFormat:#"EGK_%# ", [NSDate date]];
PhotodocumentsPath = [paths objectAtIndex:0];
PhotofilePath = [PhotodocumentsPath stringByAppendingPathComponent:totalName]; //Add the file name
NSData *pngData = UIImagePNGRepresentation(printingImage);
//Write image to the file directory .............
[pngData writeToFile:[self documentsPathForFileName:PhotofilePath] atomically:YES];
[photos_URL addObject:PhotofilePath];
[photos addObject:totalName];
[grid_copy addObject:[NSNumber numberWithInteger:count]];
[grids addObject:whichProduct];
[Totalamount addObject:[NSNumber numberWithInteger:amt]];
NSDictionary *plistDictionary = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects: photos,grids,grid_copy,Totalamount,nil] forKeys:[NSArray arrayWithObjects: #"Photo_URL",#"Product",#"Copy",#"Amount", nil]];
NSString *error = nil;
// create NSData from dictionary
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDictionary format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
// check is plistData exists
if(plistData)
{
// write plistData to our Data.plist file
[plistData writeToFile:plistPath atomically:YES];
}
else
{
NSLog(#"Error in saveData: %#", error);
}
NSString *string = [[NSString alloc] initWithData:plistData encoding:NSUTF8StringEncoding];
NSLog(#" plist Data %#", string);
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([segue.identifier isEqualToString:#"PhotoBucket"]){
RecipeCollectionViewController *photoBucket = [segue destinationViewController];
NSLog(#"Prepare Segue%#",photoBucket.photoCollection);
NSLog(#"Number of photos %#",photos_URL);
NSMutableArray *imgQueue = [[NSMutableArray alloc] initWithCapacity:photos_URL.count];
for (NSString* path in photos_URL) {
[imgQueue addObject:[UIImage imageWithContentsOfFile:path]];
}
photoBucket.photoCollection = imgQueue;
}
}
try this
for(int i=0;i<[filePathsArray count];i++)
{
NSString *strFilePath = [filePathsArray objectAtIndex:i];
if ([[strFilePath pathExtension] isEqualToString:#"jpg"] || [[strFilePath pathExtension] isEqualToString:#"png"] || [[strFilePath pathExtension] isEqualToString:#"PNG"])
{
NSString *imagePath = [[stringPath stringByAppendingFormat:#"/"] stringByAppendingFormat:strFilePath];
NSData *data = [NSData dataWithContentsOfFile:imagePath];
if(data)
{
UIImage *image = [UIImage imageWithData:data];
}
}
}
Hi you can fetch like this:
NSArray *pathPlist1 =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryStr1 = [pathPlist1 objectAtIndex:0];
NSString *plistLocation1 =
[documentsDirectoryStr1 stringByAppendingPathComponent:#"ImageStorage"];
NSFileManager *filemgr;
NSArray *filelist;
int i;
filemgr =[NSFileManager defaultManager];
filelist = [filemgr contentsOfDirectoryAtPath:plistLocation1 error:NULL];
NSLog(#"filelist =%lu",[filelist count]);
cacheImagesArray=[[NSMutableArray alloc] init];
cacheImagesDataArray=[[NSMutableArray alloc] init];
for (i = 0; i < [filelist count]; i++){
NSLog(#"%#", [filelist objectAtIndex: i]);
NSString *imageName=[NSString stringWithFormat:#"%#",[filelist objectAtIndex: i]];
NSString *path=[NSString stringWithFormat:#"%#/%#",plistLocation1, [filelist objectAtIndex: i]];
NSLog(#"Path is =%#",path);
NSData* data = [NSData dataWithContentsOfFile:path];
[cacheImagesDataArray addObject:data];
[cacheImagesArray addObject:imageName];
}
thanks
i have a problem for read a csv file. Only the last line of csv file is display.
However in my fetchedResultsController i have 2 lines
This is the code :
NSString * writeString;
NSInteger i = 0;
for (id object in [[self fetchedResultsController] fetchedObjects]) {
NSString * object1 = [[object valueForKey:#"object1"] description];
NSString * object2 = [[object valueForKey:#"object2"] description];
NSString * object3 = [[object valueForKey:#"object3"] description];
NSString * object4 = [[object valueForKey:#"object4"] description];
writeString = [NSString stringWithFormat:#"%#, %#, %#, %#, \n", object1, object2, object3, object4];
i++;
NSLog(#"%# - %i", writeString, i);
}
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* savePath = [paths objectAtIndex:0];
savePath = [savePath stringByAppendingPathComponent:#"myfile.csv"];
[writeString writeToFile:savePath atomically:YES encoding:NSUTF8StringEncoding error:NULL];
NSLog(#"%#", savePath);
NSString *fullPath = savePath;
[self readTitleFromCSV:fullPath AtColumn:0];
And The readTitleFromCSV method :
-(void)readTitleFromCSV:(NSString*)path AtColumn:(int)column
{
NSMutableArray *titleArray=[[NSMutableArray alloc]init];
NSString *fileDataString=[NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
NSArray *linesArray=[fileDataString componentsSeparatedByString:#"\n"];
int k=0;
for (id string in linesArray)
if(k<[linesArray count]-1){
NSString *lineString=[linesArray objectAtIndex:k];
NSArray *columnArray=[lineString componentsSeparatedByString:#","];
[titleArray addObject:[columnArray objectAtIndex:column]];
k++;
}
NSLog(#"%#",titleArray);
}
Thank you for your help.
Try to use NSMutableString instead of NSString:
NSMutableString *writeString = [NSMutableString string];
And then in the for loop:
[writeString appendString:[NSString stringWithFormat:#"%#, %#, %#, %#, \n", object1, object2, object3, object4]];
I have a URL of type: http://example.com/files/
And I need to determine what file is there (extension and name of file). Depending on extensions, I'll do something.
How can I determine it?
Try
NSString *ext = [[url lastPathComponent] pathExtension];
See https://developer.apple.com/documentation/foundation/nsstring/1407801-pathextension
You can use this code directly just passing your NSUrl and get File Extension in return.
- (NSString *)findExtensionOfFileInUrl:(NSURL *)url{
NSString *urlString = [url absoluteString];
NSArray *componentsArray = [urlString componentsSeparatedByString:#"."];
NSString *fileExtension = [componentsArray lastObject];
return fileExtension;
}
Try This,
NSURL *urll = [NSURL URLWithString:#"http://example.com/files/firstFile.com"];
NSString *filenameWithExtension = [urll lastPathComponent];
NSRange *range = [filenameWithExtension rangeOfString:#"."];
USing the substringWithRange just substring of those ....
NSString *fileName = [string substringWithRange:NSMakeRange(0, range.location)];
NSString *extension = [string substringWithRange:NSMakeRange(10, string.length - range.location-1)];
NSLog(#"%# %#", fileName, extension);
I have an iPad app which connects to a C# web service to download documents and images.
If I run it as a fresh install on the iPad, it downloads the expected documents and images. If I upload a new document and relaunch the app, it downloads it as expected. However, if I upload a new image to the server and run it again, it doesn't download the new image.
Here is the code for checking and downloading documents:
- (void)checkFiles:(NSString *)sessionID
{
fileList = [[NSMutableString alloc] init];
// get contents of doc directory
NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [directoryPaths objectAtIndex:0];
NSString *downloadsFolderString = [documentsDirectory stringByAppendingPathComponent:DOWNLOADS_FOLDER];
NSError *error = nil;
NSString* file;
NSDirectoryEnumerator* enumerator = [[NSFileManager defaultManager] enumeratorAtPath:downloadsFolderString];
while (file = [enumerator nextObject])
{
BOOL isDirectory = NO;
[[NSFileManager defaultManager] fileExistsAtPath: [NSString stringWithFormat:#"%#/%#", downloadsFolderString,file]
isDirectory: &isDirectory];
if ([file rangeOfString:#"LinkIcons"].location == NSNotFound)
{
if (!isDirectory)
{
[fileList appendString:[NSString stringWithFormat:#"%#|", file]];
}
}
}
// create string to send to server
NSString *post = [NSString stringWithFormat:#"sessionID=%#&fileList=%#&dateTime=%#&userID=%#", sessionID, fileList, timeOpened, userID];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSString *comparisonURLString = SERVER_COMPARE_URL_STRING;
NSURL *comparisonURL = [NSURL URLWithString:comparisonURLString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:comparisonURL];
[request setHTTPMethod:#"POST"];
[request addValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
// get response - list of files for download
NSHTTPURLResponse *urlResponse = nil;
error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
if (responseData)
{
NSString *requiredFilesList = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
// remove xml nodes from list
NSArray *lines = [requiredFilesList componentsSeparatedByString: #"\n"];
if (lines.count > 2)
{
// create sub array without xml nodes
NSRange theRange;
theRange.location = 2;
theRange.length = [lines count] -3;
numberOfFilesToBeDownloaded = theRange.length;
if (numberOfFilesToBeDownloaded <= 0)
{
_jobStatusLabel.text = #"Documents up to date";
}
if (numberOfFilesToBeDownloaded > 0)
{
NSArray *subArray = [lines subarrayWithRange:theRange];
[self getFiles:subArray];
}
}
}
[self checkLinks];
}
and:
- (void)getFiles:(NSArray *)filenames
{
downloadManager = [[DownloadManager alloc] init];
downloadManager.delegate = self;
NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *downloadFolder = [documentsPath stringByAppendingPathComponent:#"downloads"];
for (NSString *filename in filenames)
{
NSString *downloadFilename = [downloadFolder stringByAppendingPathComponent:filename];
NSString *baseUrlString = SERVER_DOWNLOAD_URL_STRING;
NSString *finalUrlString = [baseUrlString stringByAppendingPathComponent:[filename stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[downloadManager addDownload:downloadFilename fromUrl:[NSURL URLWithString:finalUrlString] ];
[self notifyServerFileDownloaded:filename];
}
}
And this is the corresponding code for the images:
- (void) checkLinks
{
NSMutableString *linkListOnDevice = [[NSMutableString alloc] init];
NSMutableArray *globalLinksArray = [[[NSUserDefaults standardUserDefaults] objectForKey:#"globalLinksArray"]mutableCopy];
if(globalLinksArray != nil)
{
NSLog(#"Links Array found. Contents: %#", globalLinksArray);
}
else
{
globalLinksArray = [[NSMutableArray alloc] initWithCapacity:0];
}
NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [directoryPaths objectAtIndex:0];
NSString *downloadsFolderString = [documentsDirectory stringByAppendingPathComponent:DOWNLOADS_FOLDER];
NSString *LinksFolderString = [downloadsFolderString stringByAppendingPathComponent:#"/LinkIcons"];
NSError *error = nil;
NSString* file;
NSDirectoryEnumerator* enumerator = [[NSFileManager defaultManager] enumeratorAtPath:LinksFolderString];
while (file = [enumerator nextObject])
{
BOOL isDirectory = NO;
[[NSFileManager defaultManager] fileExistsAtPath: [NSString stringWithFormat:#"%#/%#",downloadsFolderString,file]
isDirectory: &isDirectory];
if (!isDirectory)
{
[linkListOnDevice appendString:[NSString stringWithFormat:#"%#|", file]];
}
}
// create string to send to server
NSString *post = [NSString stringWithFormat:#"iconsList=%#&userID=%#", linkListOnDevice, userID];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSString *comparisonURLString = SERVER_COMPARE_LINK_ICONS_URL_STRING;
NSURL *comparisonURL = [NSURL URLWithString:comparisonURLString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:comparisonURL];
[request setHTTPMethod:#"POST"];
[request addValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
// get response - list of files for download
NSHTTPURLResponse *urlResponse = nil;
error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
NSString *requiredIconsList = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
// remove xml nodes from list
NSArray *lines = [requiredIconsList componentsSeparatedByString: #"\n"];
// create sub array without xml nodes
NSRange theRange;
theRange.location = 2;
theRange.length = [lines count] -3;
numberOfFilesToBeDownloaded += theRange.length;
NSArray *linkSubArray = [lines subarrayWithRange:theRange];
NSMutableArray *iconsArray = [[NSMutableArray alloc] initWithCapacity:0];
NSString *linkDetail;
for (linkDetail in linkSubArray) {
[globalLinksArray addObject:linkDetail];
}
[[NSUserDefaults standardUserDefaults] setObject:globalLinksArray forKey:#"globalLinksArray"];
[[NSUserDefaults standardUserDefaults] synchronize];
// separate file for download from rest of string
for (NSString *linkString in linkSubArray)
{
NSArray *spltArray = [linkString componentsSeparatedByString:#"^"];
NSString *linkIconString = spltArray[3];
[iconsArray addObject:linkIconString];
}
[self getLinks:iconsArray];
}
and:
- (void) getLinks: (NSMutableArray *) linkList
{
NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *downloadFolder = [documentsPath stringByAppendingPathComponent:#"downloads"];
for (NSString *filename in linkList)
{
NSString *downloadFilename = [downloadFolder stringByAppendingPathComponent:filename];
NSString *baseUrlString = SERVER_DOWNLOAD_URL_STRING;
NSString *finalUrlString = [baseUrlString stringByAppendingPathComponent:[filename stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[downloadManager addDownload:downloadFilename fromUrl:[NSURL URLWithString:finalUrlString] ];
}
}
Can anyone shed any light on why this works for documents but for images only on first run but not subsequently?
1) write this on didFinishLaunchingWithOptions method
NSString *savedValue = [[NSUserDefaults standardUserDefaults]
stringForKey:#"FirstTime"];
if (![savedValue isEqualToString:#"1"])
{
//Call for download image OR image downloading coding.
}
2) When image downloading complete then store value in NSUserDefaults
NSString *valueToSave = #"1";
[[NSUserDefaults standardUserDefaults]
setObject:valueToSave forKey:#"FirstTime"];
3) when next time your app is run then (1) condition is true and it not download image next time. If you want to download this then delete your app from simulator or device and clean then run the app.