NSCocoaErrorDomain Code=256 File couldn’t be opened - swift4

The file were created in old project in Objective-C.
NSKeyedArchiver* archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:dataForWrite];
[archiver encodeObject:dictVer forKey:#"cityVersionDict"];
[archiver finishEncoding];
BOOL flag = [dataForWrite writeToFile:path atomically:YES];
I want to read this file in new project in Swift4.0 by the code like this:
do {
let data = try Data.init(contentsOf: path)
} catch {
print(error)
}
then catch error:
Error Domain=NSCocoaErrorDomain Code=256 "The file “cityVersionDict.archiver” couldn’t be opened." UserInfo={NSURL=/Users/sam/Library/Developer/CoreSimulator/Devices/51CD0088-EE62-4ED0-8660-4C6486BC7823/data/Containers/Data/Application/5740ADE1-4930-4968-B86F-7E2F5F99F5F8/Library/Caches/cityVersionDict.archiver}
In Objective-C ,this file can be read normally .I already double check the path is right. but still catch error. please help, thanks

I find the problem is about the URL.
The URL must use init(fileURLWithPath: String) to created,
then Data(contentsOf: URL) can work fine.

Related

Cant create a database in a specific folder in ios

I am working on a jailbroken device and I am not developing for the app store.
I create a database in my code in the beginning using this code.
if(temporaryvariable == 0 ) {
if (![[NSFileManager defaultManager]fileExistsAtPath:#"/Library/Myapp/Storage"]) {
NSLog(#"Creating Direcotory Documents");
[[NSFileManager defaultManager] createDirectoryAtPath:#"/Library/Myapp/Storage" withIntermediateDirectories:YES attributes:nil error:nil];
}
storeURL = [NSURL fileURLWithPath:#"/Library/Myapp/Storage/my.sqlite" isDirectory:NO];
} else {
storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"my.sqlite"];
}
The code works fine if I change the db path to root/var/mobile/documents. But when I use the path given in the above code the app crashes with the following error.
Unresolved error Error Domain=NSCocoaErrorDomain Code=256 "The
operation couldn’t be completed. (Cocoa error 256.)" UserInfo=0x334a30
{NSUnderlyingException=authorization denied, NSSQLiteErrorDomain=23}
,,, {
NSSQLiteErrorDomain = 23;
NSUnderlyingException = "authorization denied"; } with store url file://localhost/Library/Myapp/Storage/my.sqlite
Abort trap: 6
I even tried changing the permissions of the storage folder but it doesn't work. Help me with this error please
EDIT:
This folder is actually the main bundle of my application on the jailbroken iphone.

PLCrashReporter - How to convert .plcrash to .crash directly from Xcode itself and save it locally

I am currently working with PLCrashReporter and need some help with converting the plcrash directly to .crash file instead of using the plcrashutil.
What i currently do is -
I simulate a crash and it creates a myapp.plcrash file.
Once that is generated i use the following on command line -
plcrashutil convert --format=iphone myapp.plcrash > app.crash
This works perfectly - But is there a way I can dont have to do this extra step and convert it to .crash directly from my code probably by importing the library or something??
Any Solutions???
Got the answer
Here is the solution if anyone else is looking for it..
PLCrashReportTextFormat textFormat = PLCrashReportTextFormatiOS;
/* Decode data */
PLCrashReport *crashLog = [[PLCrashReport alloc] initWithData: data error: &error];
if (crashLog == nil) {
NSLog(#"Could not decode crash file :%#", [[error localizedDescription] UTF8String]);
} else {
NSString* report = [PLCrashReportTextFormatter stringValueForCrashReport: crashLog withTextFormat: textFormat];
NSLog(#"Crash log \n\n\n%# \n\n\n", report);
NSString *outputPath = [documentsDirectory stringByAppendingPathComponent: #"app.crash"];
if (![report writeToFile:outputPath atomically:YES encoding:NSUTF8StringEncoding error:nil]) {
NSLog(#"Failed to write crash report");
} else {
NSLog(#"Saved crash report to: %#", outputPath);
}
}
Have you tried to symbolicate the .crash file in the new format?

Using exportAsynchronouslyWithCompletionHandler

I try to export an audio file from the iPod-Library. I want to create with this iPod-Library file an new file. In the AV Foundation Programming Guide in chapter Reading and Writing Assets there is a little example. However this code doesn't work for me. 4 errors happens
Export Status 4 Error Domain=AVFoundationErrorDomain
Code=-11800 "The operation could not be completed"
UserInfo=0x1edfa0 {NSLocalizedFailureReason=An unknown error occurred (-12124),
NSUnderlyingError=0x1ebdc0 "The operation couldn’t be completed. (OSStatus error -12124.)",
NSLocalizedDescription=The operation could not be completed}
My code
AVURLAsset *objAvUrlAsset = [[AVURLAsset alloc] initWithURL:[tempArray objectAtIndex:0] options:nil];
NSLog(#"%s objAvUrlAsset %#", __FUNCTION__, objAvUrlAsset);
NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:objAvUrlAsset];
NSLog(#"%s compatiblePresets %#", __FUNCTION__, compatiblePresets);
if ([compatiblePresets containsObject:AVAssetExportPresetAppleM4A]) {
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]
initWithAsset:objAvUrlAsset presetName:AVAssetExportPresetAppleM4A];
NSString * exportPath = [NSString stringWithFormat:#"testTrack1.M4A"];
NSURL *exportURL = [NSURL fileURLWithPath:exportPath];
exportSession.outputURL = exportURL;
exportSession.outputFileType = AVFileTypeAppleM4A;
exportSession.shouldOptimizeForNetworkUse = YES;
NSLog(#"%s export Session %#",__FUNCTION__, exportSession);
[exportSession exportAsynchronouslyWithCompletionHandler: ^(void) {
// export completed
NSLog(#"Export Status %d %#", exportSession.status, exportSession.error);
}];
[exportSession release];
}
the nslog message
-[MyLocalMusicLibrary getAllTracks] objAvUrlAsset AVURLAsset: 0x1dd5a0, URL = ipod-library://item/item.mp3?id=-212958261728896866
-[MyLocalMusicLibrary getAllTracks] compatiblePresets (
AVAssetExportPresetAppleM4A,
AVAssetExportPreset960x540,
AVAssetExportPresetLowQuality,
AVAssetExportPresetMediumQuality,
AVAssetExportPreset640x480,
AVAssetExportPresetHighestQuality,
AVAssetExportPreset1280x720
)
-[MyLocalMusicLibrary getAllTracks] export Session AVAssetExportSession: 0x1e85c0,
asset = AVURLAsset: 0x1dd5a0, URL = ipod-library://item/item.mp3?id=-212958261728896866,
presetName = AVAssetExportPresetAppleM4A, outputFileType = com.apple.m4a-audio
-[MyLocalMusicLibrary getAllTracks] Export Status 4 Error Domain=AVFoundationErrorDomain
Code=-11800 "The operation could not be completed"
UserInfo=0x1edfa0 {NSLocalizedFailureReason=An unknown error occurred (-12124),
NSUnderlyingError=0x1ebdc0 "The operation couldn’t be completed. (OSStatus error -12124.)",
NSLocalizedDescription=The operation could not be completed}
How can i fix this four errors. Do i need for this export the AVAssetReader and AVAssetWriter.
I got the same result from AVAssetExportSession, what the completely useless NSError is trying to tell you is that the path you're exporting to doesn't fully exist. You'll want to make sure that you create the path to the directory you're placing the file in using NSFileManager.
The problem for me was that I was trying to convert the file directly from the tmp directory after getting it from the UIImagePickerController
What I had to do was first save the file to the Library, then iterate over the ALAssetLibrary files to find the latest video saved. Then I converted that video to .mp4 and stored it int he application's local documents directory for use as I please.
Kind of ridiculous that this is necessary but it works.

Question on retrieving information on file in application directory?

i have a program which i can download a video file from a server to the app's directory but how do i retrieve the information about this file (mp4). I would like know the size of that file and it there a way to know when the file is being created as in a date or time? Thanks in advance
NSError *error = nil;
NSDictionary *fileInfo = [[NSFileManager defaultManager] attributesOfItemAtPath: filePath error: &error];
if ( fileInfo ) {
// examine fileInfo, see NSDictionary (NSFileAttributes) in NSFileManager.h
} else {
// handle the error
}

Error when trying to deleting a file that exist

A tester said that he got this message only once, and I can't seem to reproduce it or figure out how this message appeared. In a nut shell, my application starts a background thread and grabs data from our server. Once we are done downloading the data we store it in an xml file, so we can grab the data from this file incase we shutdown durning the parsing of the xml. Once I am done parsing the xml I delete the file. Here is my code for deleting.
-(void)deleteSavedXmlServerData
{
AppDelegate_Shared* appDelegate = (AppDelegate_Shared*)[[UIApplication sharedApplication] delegate];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *fileToLoad = [NSString stringWithFormat:#"%#/%#/upload.xml", [paths objectAtIndex:0], appDelegate.userId];
if([[NSFileManager defaultManager] fileExistsAtPath:fileToLoad] == YES)
{
NSError *error = nil;
[[NSFileManager defaultManager] removeItemAtPath:fileToLoad error:&error];
if(error != nil)
{
eNSLog(#"%s Error Parsing old data: %# info: %#", __PRETTY_FUNCTION__, error, [error userInfo]);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Problem With Syncing"
message:#"Problem reading in old data."
delegate:nil
cancelButtonTitle:#"ok"
otherButtonTitles:nil];
[alert show];
[alert release];
}
}
}
Everything seems to work perfectly, and it is not a big deal if this file does not get deleted. But I am confused why I would have an issue with deleting this file.
When I checked what the error message was this is what I got this.
-[ServerSync deleteSavedXmlServerData] Error Parsing old data: Error Domain=NSCocoaErrorDomain Code=4 UserInfo=0x11f3ed60 "Operation could not be completed. (Cocoa error 4.)" info: {
NSFilePath = "/var/mobile/Applications/CD181518-512F-4A0E-82ED-C438886E4A1D/Documents/71BD9A11-A604-6001-549C-DF6582F60124/upload.xml";
NSUserStringVariant = Remove;
}
If anyone know why if my file exist and I created it, why I cannot delete it?
Update
The question that confused me the most, is why does the first if statement say the file exist, but the error message that I get from trying to remove the file says that my file does not exist?
Reading the documentation for NSFileManager (don't know if I just missed it the first time), it says to not use the singleton method [NSFileManager defaultManager] because NSFileManager is not thread safe. I have not had this problem since then.
It looks like the document directory path is /.../71BD9A11-A604-6001-549C-DF6582F60124CD181518-512F-4A0E-82ED-C438886E4A1D/Documents/71BD9A11-A604-6001-549C-DF6582F60124. It should end in /Documents.
Googling for NSCocoaErrorDomain gives NSFileNoSuchFileError = 4.
Testing for file existence before removing it suffers from a race condition as another thread can come in and remove it before the deletion code executes. It would be better to refactor your code to remove the file first and ignore any "errors" related to file not found.
BTW: the answer regarding [NSFileManager defaultManager] not being thread safe is not entirely true. It is thread safe except when using a delegate for notifications.
According to this answer
NSFileManager: removing item
we need to have a file:// prefix. You can use [NSURL fileURLWithPath:] to achieve it.
For swift use NSURL(fileURLWithPath: realmPath)