I have NSData object,it contains 16300 bytes and I am writing to file. Write is success full. But once I want to read from path again, it gives me only 44 bytes.
//writing to path
[audioData writeToFile:recorderFilePath options:NSDataWritingAtomic error:&err];
if (err) {
NSLog(#"Error of writing to file %#",[err localizedDescription]);
}
// reading from path
NSData *paddata = [NSData dataWithContentsOfFile:filePath];
Any help will be appreciated.
Thank you.
Just below code used for write your audio file and read from path.
Write audio file to path
[fileData writeToFile:audioFilePath atomically:YES];
reading from path
NSURL *soundFileURL = [NSURL fileURLWithPath:audioFilePath];
Related
In the recorder application,I'm trying to capture the stereo speech data into a file.
for ( int i=0; i<bufferList->mNumberBuffers; i++ ) {
memcpy(bufferList->mBuffers[i].mData, audio->mBuffers[i].mData, byteCount);
}
The above code contains the recorded speech data. The file writing goes as below.
NSString *root = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *filePath = [root stringByAppendingPathComponent:#"mic_in.raw"];
if(![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
[[NSData data] writeToFile:filePath atomically:YES];
}
NSData *myData = [NSData dataWithBytes:audio->mBuffers[0].mData length:byteCount];
NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:filePath];
[handle truncateFileAtOffset:[handle seekToEndOfFile]];
[handle writeData:myData];
myData = [NSData dataWithBytes:audio->mBuffers[1].mData length:byteCount];
[handle truncateFileAtOffset:[handle seekToEndOfFile]];
[handle writeData:myData];
[handle closeFile];
The 'stereo' speech is recorded in 'non interleaved' format.
The saved file contents are not proper. (For e.g. for 15 seconds of speech data, only 2.5 is saved. Saved data also not proper)
The file writing for 'Mono' speech is working fine.
I'm not sure, what is wrong in the 'stereo' speech file writing?
the issue of stereo file writing got it resolved, as follows.
The very frequent file operations at callback was causing the data loss.
So, in callback, the data (after interleaving conversion) is saved in a big buffer and at the end of speech recording, the complete buffer content is written into a file at one shot.
The above approach, resolved the stereo file capturing issue.
I building a Mac app,I have 2 problem:
I want to create a text file to read and write data on it. I don't know how to crate a text file to read and write data. Is it use
struct?
I want to create a XML file to read and write data on it. Can I create a struct for XML?
Do you have suggestion? Thanks in advance
Well, to create a file, just use
[[NSFileManager defaultManager] createFileAtPath:#"Your/Path" contents:nil attributes:nil];
This creates an empty file, which you can write to or read from. To write text (or XML), just use NSString's writeToFile:atomically:encoding:error: method like this
NSString *str = //Your text or XML
[str writeToFile:"Your/Path" atomically:YES encoding:NSUTF8StringEncoding error:nil];
To read from a file, just make an NSString with the contents of that file
NSString *contents = [NSString stringWithContentsOfFile:#"Your/Path"];
or, if it does not contain a string, get an NSData object from the file
NSData *contents = [NSData dataWithContentsOfFile:#"Your/Path"];
/**************************main.m******************************
NS FILE HANDLE READ & WRITE
reading and writing in same file
Created by abdulsathar on 6/16/14.
***************************************************************/
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
#autoreleasepool //ARC
{
NSFileHandle *file;
//object for File Handle
NSError *error;
//crearing error object for string with file contents format
NSMutableData *writingdatatofile;
//create mutable object for ns data
NSString *filePath=[NSString stringWithFormat:#"/Users/chandrakumar/Documents/abdul/doc.txt"];
//telling about File Path for Reading for easy of access
file = [NSFileHandle fileHandleForReadingAtPath:#"/Users/chandrakumar/Documents/abdul/doc.txt"];
//assign file path directory
if (file == nil) //check file exist or not
NSLog(#"Failed to open file");
NSString *getfileContents = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
//access file contents with out ns handle method
if (error) //check error flag for file present or not
NSLog(#"Error reading file: %#", error.localizedDescription);
NSLog(#"contents: %#", getfileContents);
//display file contents in main file
NSArray *listArray = [getfileContents componentsSeparatedByString:#"\n"];
//caluculate list of line present in files
NSLog(#"items = %ld", [listArray count]);
const char *writingchar = "how are you";
writingdatatofile = [NSMutableData dataWithBytes:writingchar length:strlen(writingchar)];
//convert string format into ns mutable data format
file = [NSFileHandle fileHandleForUpdatingAtPath: #"/Users/chandrakumar/Documents/abdul/new.txt"];
//set writing path to file
if (file == nil) //check file present or not in file
NSLog(#"Failed to open file");
[file seekToFileOffset: 6];
//object pointer initialy points the offset as 6 position in file
[file writeData: writingdatatofile];
//writing data to new file
[file closeFile];
//close the file
}
return 0;`enter code here`
}
/***********************************OUTPUT********************************************
2014-06-17 14:55:39.695 storage[4075:303] contents: hello how are you my dearservice
*************************************************************************************/
I am a beginner using Objective-C. I used the following code to move a file to iCloud but it gives an error that The operation could not be completed. The file exists.
//store the file locally in document folder
NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [docPaths objectAtIndex:0];
filePath = [filePath stringByAppendingString:#"/"];
filePath = [filePath stringByAppendingString:fileName];
NSString *writeError = nil;
NSData * fileData = [NSPropertyListSerialization dataFromPropertyList:dataDic format:NSPropertyListXMLFormat_v1_0 errorDescription:&writeError];
if ([fileData writeToFile:filePath atomically:YES]) {
NSLog(#"Server file is stored locally");
}else {
NSLog(#"%#", writeError);
}
// store the file in iCloud folder
NSURL *ubiquitousURL = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
NSString *tmpubiquitousURL = ubiquitousURL.absoluteString;
tmpubiquitousURL = [tmpubiquitousURL stringByAppendingString:fileName];
NSURL *ubi2 = [[NSURL alloc] initWithString:tmpubiquitousURL];
[[NSFileManager defaultManager] setUbiquitous:YES itemAtURL:filePathURL destinationURL:ubi2 error:&error];
I used the following to remove the file from iCloud but it gives an error that Cannot disable syncing on an un-synced file.
[[NSFileManager defaultManager] setUbiquitous:NO itemAtURL:filePathURL destinationURL:ubi2 error:&error];
I checked the availability of iCloud in my app delegate and it's available. The file is an XML file (.plist) and I have a local copy stored in NSDocumentDirectory.
Overall, I want to sync that file in iCloud so it will be accessible on all devices using my app. I have been struggling with this for 2 days, so if you could help me to resolve the problem I would appreciate it.
Note: I would rather not to use UIDocument, however, if that is the only option please let me know.
I also have the same problem while using the code
[[NSFileManager defaultManager] setUbiquitous:NO itemAtURL:filePathURL destinationURL:ubi2 error:&error];
you have to change the code like below for this to work correctly
[[[NSFileManager alloc]init]setUbiquitous:YES itemAtURL:filePathURL destinationURL:ubi2 error:nil];
this code is for moving a file to icloud, also you should change the name of the file you are moving. It should not be same.
I have a log file that I'm trying to append data to the end of. I have an NSMutableString textToWrite variable, and I am doing the following:
[textToWrite writeToFile:filepath atomically:YES
encoding: NSUnicodeStringEncoding error:&err];
However, when I do this all the text inside the file is replaced with the text in textToWrite. How can I instead append to the end of the file? (Or even better, how can I append to the end of the file on a new line?)
I guess you could do a couple of things:
NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:aPath];
[fileHandle seekToEndOfFile];
[fileHandle writeData:[textToWrite dataUsingEncoding:NSUTF8StringEncoding]];
[fileHandle closeFile];
Note that this will append NSData to your file -- NOT an NSString. Note that if you use NSFileHandle, you must make sure that the file exists before hand. fileHandleForWritingAtPath will return nil if no file exists at the path. See the NSFileHandle class reference.
Or you could do:
NSString *contents = [NSString stringWithContentsOfFile:filepath];
contents = [contents stringByAppendingString:textToWrite];
[contents writeToFile:filepath atomically:YES encoding: NSUnicodeStringEncoding error:&err];
I believe the first approach would be the most efficient, since the second approach involves reading the contents of the file into an NSString before writing the new contents to the file. But, if you do not want your file to contain NSData and prefer to keep it text, the second option will be more suitable for you.
[Update]
Since stringWithContentsOfFile is deprecated you can modify second approach:
NSError* error = nil;
NSString* contents = [NSString stringWithContentsOfFile:filepath
encoding:NSUTF8StringEncoding
error:&error];
if(error) { // If error object was instantiated, handle it.
NSLog(#"ERROR while loading from file: %#", error);
// …
}
[contents writeToFile:filepath atomically:YES
encoding:NSUnicodeStringEncoding
error:&err];
See question on stackoverflow
Initially I thought that using the FileHandler method in the accepted answer that I was going to get a bunch of hex data values written to my file, but I got readable text which is all I need. So based off the accepted answer, this is what I came up with:
-(void) writeToLogFile:(NSString*)content{
content = [NSString stringWithFormat:#"%#\n",content];
//get the documents directory:
NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *fileName = [documentsDirectory stringByAppendingPathComponent:#"hydraLog.txt"];
NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:fileName];
if (fileHandle){
[fileHandle seekToEndOfFile];
[fileHandle writeData:[content dataUsingEncoding:NSUTF8StringEncoding]];
[fileHandle closeFile];
}
else{
[content writeToFile:fileName
atomically:NO
encoding:NSUTF8StringEncoding
error:nil];
}
}
This way if the file doesn't yet exist, you create it. If it already exists then you only append to it. Also, if you go into the plist and add a key under the information property list UIFileSharingEnabled and set the value to true then the user can sync with their computer and see the log file through iTunes.
And here is a (slightly adopted) Swift version of Chase Roberts' solution:
static func writeToFile(content: String, fileName: String = "log.txt") {
let contentWithNewLine = content+"\n"
let filePath = NSHomeDirectory() + "/Documents/" + fileName
let fileHandle = NSFileHandle(forWritingAtPath: filePath)
if (fileHandle != nil) {
fileHandle?.seekToEndOfFile()
fileHandle?.writeData(contentWithNewLine.dataUsingEncoding(NSUTF8StringEncoding)!)
}
else {
do {
try contentWithNewLine.writeToFile(filePath, atomically: true, encoding: NSUTF8StringEncoding)
} catch {
print("Error while creating \(filePath)")
}
}
}
i am trying to read jpg file and convert into byte array
this is the following code this code works fine with text file but files on image files
// start code
NSString *stringFromFileAtPath = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
if(stringFromFileAtPath == nil){
NSLog(#"Error reading file at path %#\n%#", path, [error localizedFailureReason]);
}
NSLog(#"Contents:%#", stringFromFileAtPath);
NSData *bytes = [stringFromFileAtPath dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#"Bytes:%#", bytes);
// end of code
and this is error message i am getting
Error Message:Text encoding Unicode (UTF-8) isn’t applicable.
Let me know what is the error i am doing or code to convert jpg file to byte array
Why not just use NSData's initWithContentsOfFile: method? See here:
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/Reference/Reference.html
i.e.:
NSData *bytes = [[NSData alloc] initWithContentsOfFile:path];
NSLog(#"Bytes:%#", bytes);
The reason you can't do what you did is that you're trying to read the image file as if it is encoded in UTF8, which it's highly likely there's bytes in there that would be malformed in UTF8 - it's not a string.