Saving text file to documents directory in iOS 7

后端 未结 3 354
死守一世寂寞
死守一世寂寞 2020-12-08 08:02

I am trying to save a plain text file to the Documents directory in iOS 7. Here is my code:

//Saving file
NSFileManager *fileManager = [[NSFileManager alloc]         


        
3条回答
  •  鱼传尺愫
    2020-12-08 08:40

        -(void)writeATEndOfFile:(NSString *)content2
        {
            NSArray *paths = NSSearchPathForDirectoriesInDomains
            (NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *documentsDirectory = [paths objectAtIndex:0];
    
            //make a file name to write the data to using the documents directory:
            NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt",
                                  documentsDirectory];
    
            if([[NSFileManager defaultManager] fileExistsAtPath:fileName])
            {
                NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:fileName];
                [fileHandle seekToEndOfFile];
                NSString *writedStr = [[NSString alloc]initWithContentsOfFile:fileName encoding:NSUTF8StringEncoding error:nil];
                content2 = [content2 stringByAppendingString:@"\n"];
                writedStr = [writedStr stringByAppendingString:content2];
    
                [writedStr writeToFile:fileName
                            atomically:NO
                              encoding:NSStringEncodingConversionAllowLossy
                                 error:nil];
            }
            else {
                int n = [content2 intValue];
                [self writeToTextFile:n];
            }
    
        }   
    
    
     -(void) writeToTextFile:(int) value{
            //get the documents directory:
            NSArray *paths = NSSearchPathForDirectoriesInDomains
            (NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *documentsDirectory = [paths objectAtIndex:0];
    
            //make a file name to write the data to using the documents directory:
            NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt",
                                  documentsDirectory];
            //create content - four lines of text
           // NSString *content = @"One\nTwo\nThree\nFour\nFive";
    
            NSString *content2 = [NSString stringWithFormat:@"%d",value];
            content = [content2 stringByAppendingString:@"\n"];
            //save content to the documents directory
            [content writeToFile:fileName
                      atomically:NO
                        encoding:NSStringEncodingConversionAllowLossy
                           error:nil];
    
        }
    

提交回复
热议问题