Access local file path in Objective C - ios

I have added a folder name Resources and under it there is another folder name File inside the file folder there are two xml files which i'm trying to parse. When i give pathforResource method name to my Resources folder it shows path is null. How can i access the two xml file from these folders?
Resources->File->text.xml.
My code is this,
NSMutableArray *aryXMLName = [NSMutableArray new];
[aryXMLName addObject:#"text.xml"];
[aryXMLName addObject:#"test1.xml"];
for(NSString *str in aryXMLName){
NSString *path = [[NSBundle mainBundle] pathForResource:str ofType:#"Resources"];
NSLog(#"Path : %#",path);
NSData *data=[NSData dataWithContentsOfFile:path];
if ([str isEqualToString:#"text.xml"]) {
if (data == nil)
return;
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"string: %#", str);
NSDictionary *xmlDoc = [NSDictionary dictionaryWithXMLString:str];
NSLog(#"dictionary: %#", xmlDoc);
}else if ([str isEqualToString:#"test1.xml"]){
if (data == nil)
return;
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"string: %#", str);
NSDictionary *xmlDoc = [NSDictionary dictionaryWithXMLString:str];
NSLog(#"dictionary: %#", xmlDoc);
}
}
The scenario is like this,
enter image description here

Replace this code:
NSMutableArray *aryXMLName = [NSMutableArray new];
[aryXMLName addObject:#"test"];
[aryXMLName addObject:#"text1"];
for(NSString *str in aryXMLName){
NSString *path = [[NSBundle mainBundle] pathForResource:str ofType:#"xml"];
NSLog(#"Path : %#",path);
NSData *data=[NSData dataWithContentsOfFile:path];
if ([str isEqualToString:#"test"]) {
if (data == nil)
return;
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"string: %#", str);
NSDictionary *xmlDoc = [NSDictionary dictionaryWithXMLString:str];
NSLog(#"dictionary: %#", xmlDoc);
}else if ([str isEqualToString:#"text1"]){
if (data == nil)
return;
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"string: %#", str);
NSDictionary *xmlDoc = [NSDictionary dictionaryWithXMLString:str];
NSLog(#"dictionary: %#", xmlDoc);
}
}

Related

App crashes in iOS7 but not in 8 &9 due to NSDictionary autorelease

+ (NSString *)getValueforLocale:(NSString*) i18nkey :(NSString*)locale{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSLog(#"paths are : %#",paths);
NSString *libraryDirectory = [paths objectAtIndex:0];
NSLog(#"libraryDirectory : %#",libraryDirectory);
NSString *filePath = [libraryDirectory stringByAppendingPathComponent:#"I8nDB"];
filePath = [filePath stringByAppendingPathComponent:locale];
NSLog(#"file path is : %#",filePath);
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
if(fileExists)
{
NSDictionary *dict = [[[NSDictionary alloc] initWithContentsOfFile:filePath]autorelease];
NSDictionary *resourceBundle = [[[NSDictionary alloc] init]autorelease];
NSString *keyValue = [[[NSString alloc]init]autorelease];
resourceBundle = [dict valueForKey:#"hash"];
keyValue=[resourceBundle valueForKey:i18nkey];
NSLog(#"value for %# is(container) : %#",i18nkey,keyValue);
if(keyValue != nil || keyValue != NULL)
{
return keyValue;
}
else
{
NSLog(#"key not found in the container file");
NSString *path = [[NSBundle mainBundle] pathForResource:#"Localizable"
ofType:#"strings"
inDirectory:nil
forLocalization:locale];
NSLog(#"path for %# is : %#",locale,path);
fileExists = [[NSFileManager defaultManager] fileExistsAtPath:path];
if(fileExists)
{
NSDictionary *dict = [[NSDictionary dictionaryWithContentsOfFile:path]autorelease];
NSLog(#"value for %# is(resources) : %#",i18nkey,[dict objectForKey:i18nkey]);
return [dict objectForKey:i18nkey];
}
else
{
return NULL;
}
}
}
else
{
NSLog(#"%# locale does not exist in container",locale);
NSString *path = [[NSBundle mainBundle] pathForResource:#"Localizable"
ofType:#"strings"
inDirectory:nil
forLocalization:locale];
NSLog(#"path for %# in resources is : %#",locale,path);
fileExists = [[NSFileManager defaultManager] fileExistsAtPath:path];
if(fileExists)
{
NSDictionary *dict = [[NSDictionary dictionaryWithContentsOfFile:path]autorelease];
NSLog(#"value for %# is : %#",i18nkey,[dict objectForKey:i18nkey]);
return [dict objectForKey:i18nkey];
}
else
{
return NULL;
}
}
}
If we remove Autorelease from the above code, it is working in iOS7 if not the app is crashing
My Main concern is why it doesn't crash in iOS8&9 and only crashes in iOS7
is there in change related to autorelease over these versions
Why don't you use ARC? Then you won't need autorelease...
See http://rypress.com/tutorials/objective-c/memory-management
Your problem might be related to the settings about ARC.
in Your code you only alloc a dictionary in
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:filePath];
so you only need to care about it, another object is not owned by You! so You don't need release or autorelease them.
Try flowing code
+ (NSString *)getValueforLocale:(NSString*) i18nkey :(NSString*)locale
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSLog(#"paths are : %#",paths);
NSString *libraryDirectory = [paths objectAtIndex:0];
NSLog(#"libraryDirectory : %#",libraryDirectory);
NSString *filePath = [libraryDirectory stringByAppendingPathComponent:#"I8nDB"];
filePath = [filePath stringByAppendingPathComponent:locale];
NSLog(#"file path is : %#",filePath);
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
if(fileExists)
{
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:filePath];
//NSDictionary *resourceBundle = [[[NSDictionary alloc] init]autorelease];
//NSString *keyValue = [[[NSString alloc]init]autorelease];
NSDictionary *resourceBundle = [dict valueForKey:#"hash"];
// relese dict here because not use after
[dict release];
NSString *keyValue=[resourceBundle valueForKey:i18nkey];
NSLog(#"value for %# is(container) : %#",i18nkey,keyValue);
if(keyValue != nil || keyValue != NULL)
{
return keyValue;
}
else
{
NSLog(#"key not found in the container file");
NSString *path = [[NSBundle mainBundle] pathForResource:#"Localizable"
ofType:#"strings"
inDirectory:nil
forLocalization:locale];
NSLog(#"path for %# is : %#",locale,path);
fileExists = [[NSFileManager defaultManager] fileExistsAtPath:path];
if(fileExists)
{
// NSDictionary *dict = [[NSDictionary dictionaryWithContentsOfFile:path]autorelease];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
NSLog(#"value for %# is(resources) : %#",i18nkey,[dict objectForKey:i18nkey]);
return [dict objectForKey:i18nkey];
}
else
{
return NULL;
}
}
}
else
{
NSLog(#"%# locale does not exist in container",locale);
NSString *path = [[NSBundle mainBundle] pathForResource:#"Localizable"
ofType:#"strings"
inDirectory:nil
forLocalization:locale];
NSLog(#"path for %# in resources is : %#",locale,path);
fileExists = [[NSFileManager defaultManager] fileExistsAtPath:path];
if(fileExists)
{
// NSDictionary *dict = [[NSDictionary dictionaryWithContentsOfFile:path]autorelease];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
NSLog(#"value for %# is : %#",i18nkey,[dict objectForKey:i18nkey]);
return [dict objectForKey:i18nkey];
}
else
{
return NULL;
}
}
}
In manual reference counting, retains and releases need to be balanced.
In
NSDictionary *dict = [[[NSDictionary alloc] initWithContentsOfFile:filePath]autorelease];
NSDictionary *resourceBundle = [[[NSDictionary alloc] init]autorelease];
the retains and releases are balanced, because alloc (along with retain, new, copy, mutableCopy) returns a retained instance, and autorelease counts as a release.
However, in
NSDictionary *dict = [[NSDictionary dictionaryWithContentsOfFile:path]autorelease];
you have an overrelease because you are autorelease something that you have not retained.
iOS version has absolutely nothing to do with it.

How to Access local JSON file response in NSDictionary for showing in UITableView?

Basically I got response from server side and then i saved it in local file.Actually I fetched the response from server side and then saved into documents directory ,and now trying to fetch but it comes in NSString only ,i unable to get in NSDictionary....Here is following code
- (IBAction)loginButtonPressed:(id)sender
{
NSString *URLString = #"http://localhost/rest/login";
AFHTTPSessionManager *manager =[AFHTTPSessionManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
NSDictionary *params = #{#"username": userNameTxtField.text, #"password": pwdTextField.text};
NSLog(#"Parameters:\n%#",params);
[manager POST:URLString parameters:params progress:nil success:^(NSURLSessionDataTask *operation, id responseObject)
{
NSLog(#"Successfully Login ....: %#", responseObject);
NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
path = [NSString stringWithFormat:#"%#/sample.json", documents];
NSOutputStream *stream = [[NSOutputStream alloc] initToFileAtPath:path append:YES];
[stream open];
NSError *writeError = nil;
NSInteger bytesWritten = [NSJSONSerialization writeJSONObject:responseObject toStream:stream options:NSJSONWritingPrettyPrinted error:&writeError];
if ((bytesWritten = 0))
{
NSLog(#"Error writing JSON Data");
}
else{
NSLog(#"Sucessfuly saved data...");
}
[stream close];
NSLog(#"path is :%#",path);
} failure:^(NSURLSessionDataTask *operation, NSError *error)
{
NSLog(#"Error: %#", error);
}];
}
- (IBAction)fetch:(id)sender
{
NSError *deserializingError;
NSData *data=[NSData dataWithContentsOfFile:path];
NSString *jsonString = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&deserializingError];
NSMutableDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(#"vaues are:%#",dict);
}
Your response object should be a type of NSDictionary. Therefore you can use its writeToFileAtPath method to save it to your documents directory.
When recreating the dictionary, you can use the NSDictionary's alloc and initWithContentsOfFile method to directly create a NSDictionary instance.
There are tons of posts on how to do that if you do a little Google search!
Try this!! It's working fine.
NSMutableDictionary *testStore = [[NSMutableDictionary alloc] init];
[testStore setObject:#"vignesh" forKey:#"username"];
[testStore setObject:#"password" forKey:#"password"];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:testStore // Here you can pass array or dictionary
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:&error];
NSString *jsonString;
if (jsonData) {
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
//This is your JSON String
//NSUTF8StringEncoding encodes special characters using an escaping scheme
} else {
NSLog(#"Got an error: %#", error);
jsonString = #"";
}
[self writeStringToFile:jsonString];
NSLog(#"Your JSON String is %#", [self readStringFromFile]);
- (void)writeStringToFile:(NSString*)aString {
// Build the path, and create if needed.
NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* fileName = #"bookmark.json";
NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName];
if (![[NSFileManager defaultManager] fileExistsAtPath:fileAtPath]) {
[[NSFileManager defaultManager] createFileAtPath:fileAtPath contents:nil attributes:nil];
}
// Write to file
[[aString dataUsingEncoding:NSUTF8StringEncoding] writeToFile:fileAtPath atomically:NO];
}
- (NSString*)readStringFromFile {
// Build the path...
NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* fileName = #"bookmark.json";
NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName];
// read from file
return [[NSString alloc] initWithData:[NSData dataWithContentsOfFile:fileAtPath] encoding:NSUTF8StringEncoding];
}
static const char *dbPath = nil;
static sqlite3_stmt *ermsg = nil;
static sqlite3 *studs =nil;
static DatabaseOperation *_sharedInstances = nil;
#implementation DatabaseOperation
#synthesize databasePath;
+(DatabaseOperation*)sharedInstances{
if(!_sharedInstances){
_sharedInstances =[[super allocWithZone:nil]init];
}
return _sharedInstances;
}
+(id)allocWithZone:(struct _NSZone *)zone{
return [self sharedInstances];
}
-(id)init{
NSLog(#"Only first time Instances using Singleton:");
self =[super init];
if(self){
[self CreateDbpath];
}
return self;
}
-(BOOL)CreateDbpath{
NSArray *dbpaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docdir=[[NSString alloc]initWithString:[dbpaths objectAtIndex:0]];
self.databasePath =[[NSString alloc]initWithString:[docdir stringByAppendingPathComponent:#"Mindset.sqlite"]];
NSFileManager *flg = [NSFileManager defaultManager];
BOOL isSuccess = false;
if([flg fileExistsAtPath:databasePath]==NO){
char *ermsgss = nil;
char const *dbpathss =[self.databasePath UTF8String];
if(sqlite3_open(dbpathss, &studs)==SQLITE_OK){
char *sqlQuery ="create table if not exists emp(name text,city text,img blob)";
if(sqlite3_exec(studs, sqlQuery, nil, nil, &ermsgss)!=SQLITE_OK){
NSLog(#"Failed to create table:");
}
else{
NSLog(#"Successfully to create table:");
}
}
sqlite3_close(studs);
}
return isSuccess;
}
-(void)insertDatabaseValue:(DataManagers *)getInserted{
dbPath = [self.databasePath UTF8String];
if(sqlite3_open(dbPath, &studs)==SQLITE_OK){
NSString *sqlQuery=[[NSString alloc]initWithFormat:#"insert into emp values(?,?,?)"];
const char *_sqlQuery=[sqlQuery UTF8String];
if(sqlite3_prepare_v2(studs, _sqlQuery, -1, &ermsg, nil)==SQLITE_OK){
sqlite3_bind_text(ermsg, 1, [getInserted.userName UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(ermsg, 2, [getInserted.cityName UTF8String], -1, SQLITE_TRANSIENT);
NSData *jpegData =[[NSData alloc]init];
NSData *imgeData =UIImageJPEGRepresentation(getInserted.profileImg, 0.85f);
UIImage *imgesData =[UIImage imageWithData:imgeData];
CGRect rect = CGRectMake(0, 0, 185, 150);
UIGraphicsBeginImageContext(rect.size);
[imgesData drawInRect:rect];
UIImage *img =UIGraphicsGetImageFromCurrentImageContext()
;
UIGraphicsEndImageContext();
jpegData = UIImageJPEGRepresentation(img, 0.01f);
sqlite3_bind_blob(ermsg, 3, [jpegData bytes], [jpegData length], SQLITE_TRANSIENT);
if(sqlite3_step(ermsg)==SQLITE_DONE){
NSLog(#"Successfully inserted into db:");
}
else {
NSLog(#"Error %s",sqlite3_errmsg(studs));
}
}
sqlite3_close(studs);
sqlite3_finalize(ermsg);
}
}
-(NSMutableArray*)getAllData {
NSMutableArray *array =[[NSMutableArray alloc]init];
dbPath = [self.databasePath UTF8String];
if(sqlite3_open(dbPath, &studs)==SQLITE_OK){
NSString *sqlQuery =[[NSString alloc]initWithFormat:#"select * from emp"];
const char *_sqlQuery =[sqlQuery UTF8String];
if(sqlite3_prepare_v2(studs, _sqlQuery, -1, &ermsg, nil)==SQLITE_OK){
while (sqlite3_step(ermsg)==SQLITE_ROW) {
DataManagers *mgr =[[DataManagers alloc]init];
NSString *_Firstname = (const char*)sqlite3_column_text(ermsg, 0) ? [NSString stringWithUTF8String:(const char*)sqlite3_column_text(ermsg, 0)]:nil;
mgr.userName = _Firstname;
NSString *lastName =(const char*)sqlite3_column_text(ermsg, 1)?[NSString stringWithUTF8String:(const char*)sqlite3_column_text(ermsg, 1)]:nil;
mgr.cityName = lastName;
int imgBytes = sqlite3_column_bytes(ermsg, 2);
UIImage *img =[UIImage imageWithData:[NSData dataWithBytes:sqlite3_column_blob(ermsg, 2) length:imgBytes]];
mgr.profileImg = img;
[array addObject:mgr];
}
}
}
return array;
}

Xcode - Special characters in JSON

Im loading a database from a website through JSON. When I download the database I use UTF8 to make all characters appear correctly and when I NSLOG them it all appears as it should. But when I analyze the data using JSON and afterwards try to filter out just a few of the words, the words with special characters become like this: "H\U00f6ghastighetst\U00e5g" where it should say: "Höghastighetståg".
I have tried to find a way to make the code convert the text back to UTF8 after filtering but somehow I can't make it happen. Would be really helpful for some answers.
NSError *error;
NSString *url1 = [NSString stringWithContentsOfURL:[NSURL URLWithString:#"http://www.pumba.se/example.json"] encoding:NSUTF8StringEncoding error:&error];
NSLog(#"Before converting to NSData: %#", url1);
NSData *allCoursesData = [url1 dataUsingEncoding:NSUTF8StringEncoding];
NSMutableDictionary *JSONdictionary = [NSJSONSerialization
JSONObjectWithData:allCoursesData
options:kNilOptions
error:&error];
if( error )
{
NSLog(#"%#", [error localizedDescription]);
}
else {
NSMutableArray *allNames = [NSMutableArray array];
NSArray* entries = [JSONdictionary valueForKeyPath:#"hits.hits"];
for (NSDictionary *hit in entries) {
NSArray *versions = hit[#"versions"];
for (NSDictionary *version in versions) {
NSDictionary *properties = version[#"properties"];
NSString *status = [properties[#"Status"] firstObject];
NSString *name = [properties[#"Name"] firstObject];
if ([status isEqualToString:#"usable"]) {
[allNames addObject:name];
}
}
}
NSLog(#"All names: %#", allNames);
}}
try with
+ (NSString *)utf8StringEncoding:(NSString *)message
{
NSString *uniText = [NSString stringWithUTF8String:[message UTF8String]];
NSData *msgData = [uniText dataUsingEncoding:NSNonLossyASCIIStringEncoding];
message = [[NSString alloc] initWithData:msgData encoding:NSUTF8StringEncoding];
return message;
}
or
+ (NSString *)asciiStringEncoding:(NSString *)message
{
const char *jsonString = [message UTF8String];
NSData *jsonData = [NSData dataWithBytes:jsonString length:strlen(jsonString)];
message = [[NSString alloc] initWithData:jsonData encoding:NSNonLossyASCIIStringEncoding];
return message;
}
and this code can help you
+ (NSDictionary *)jsonStringToObject:(NSString *)jsonString
{
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonResponse;
if (data)
jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
return jsonResponse;
}
+ (NSString *)objectToJsonString:(NSDictionary *)dict
{
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
if (jsonData.length > 0 && !error)
{
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
return jsonString;
}
return nil;
}

How to transfer encrypted data over AirDrop

I want to transfer my NSObject "RND_PatientData" which is encrypted from my application to another person using the application using AirDrop.
At present my data is saved using this code:
- (RND_PatientData *)data {
if (_data != nil) return _data;
NSString *dataPath = [_docPath stringByAppendingPathComponent:kDataFile];
NSData *codedData = [[NSData alloc] initWithContentsOfFile:dataPath];
if (codedData == nil) return nil;
NSString *deviceName = [[UIDevice currentDevice] name];
NSData *decryptedData = [RNDecryptor decryptData:codedData withSettings:kRNCryptorAES256Settings password:deviceName error:nil];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:decryptedData];
_data = [unarchiver decodeObjectForKey:kDataKey];
[unarchiver finishDecoding];
return _data;
}
- (void)saveData {
if (_data == nil) return;
[self createDataPath];
NSString *dataPath = [_docPath stringByAppendingPathComponent:kDataFile];
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:_data forKey:kDataKey];
[archiver finishEncoding];
NSError *error;
NSString *deviceName = [[UIDevice currentDevice] name];
NSData *encryptedData = [RNEncryptor encryptData:data
withSettings:kRNCryptorAES256Settings
password:deviceName
error:&error];
[encryptedData writeToFile:dataPath atomically:YES];
This data is also encrypted using the device UDID and the RNDecryptor library before being saved.
Now, I would like the perosn to be able to transfer the data via AirDrop.
Is it better to decrypt the data on the sender phone and then transfer it unencrypted and encrypt it on the receiver phone using the same framework or to transfer it encrypted and decrypt it using the sender device UDID?
I load my current data as a NSMutableArray :
_patients = [RND_PatientDB loadDocs];
The method goes as follow:
+ (NSMutableArray *)loadDocs {
// Get private docs dir
NSString *documentsDirectory = [RND_PatientDB getPrivateDocsDir];
NSLog(#"Loading patients from %#", documentsDirectory);
// Get contents of documents directory
NSError *error;
NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:&error];
if (files == nil) {
NSLog(#"Error reading contents of documents directory: %#", [error localizedDescription]);
return nil;
}
// Create Patients for each file
NSMutableArray *retval = [NSMutableArray arrayWithCapacity:files.count];
for (NSString *file in files) {
if ([file.pathExtension compare:#"patients" options:NSCaseInsensitiveSearch] == NSOrderedSame) {
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:file];
RND_Patient *doc = [[RND_Patient alloc] initWithDocPath:fullPath];
[retval addObject:doc];
}
}
return retval;
}
+ (NSString *)nextPatientDocPath {
// Get private docs dir
NSString *documentsDirectory = [RND_PatientDB getPrivateDocsDir];
// Get contents of documents directory
NSError *error;
NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:&error];
if (files == nil) {
NSLog(#"Error reading contents of documents directory: %#", [error localizedDescription]);
return nil;
}
// Search for an available name
int maxNumber = 0;
for (NSString *file in files) {
if ([file.pathExtension compare:#"patients" options:NSCaseInsensitiveSearch] == NSOrderedSame) {
NSString *fileName = [file stringByDeletingPathExtension];
maxNumber = MAX(maxNumber, fileName.intValue);
}
}
// Get available name
NSString *availableName = [NSString stringWithFormat:#"%d.patients", maxNumber+1];
return [documentsDirectory stringByAppendingPathComponent:availableName];
}
I've tried following instructions here to send NSArray via AirDrop, but I cannot understand how the certificate works. Anyone has ressources I can use to learn more about this procedure? Also am I doing it the right way or is there an easier method to send my NSMutableArray of _patients comprised of RND_PATIENT NSObject to another person using my application?

How to concatenate/merge data of three textfiles into one textfiles in iOS

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);
}

Resources