Can I use a NSData file from OS X in iOS - ios

I have a level editor for my iOS App and it's running on OS X. It saves the levels in an archived NSData-Object. These files are inside my apps bundle and I try to load them on the iOS app using:
NSString* path_ = [dictionary_ objectForKey:kWDLevelController_Level_PathKey];
NSString* sourcePath_ = [[NSBundle mainBundle] pathForResource:path_ ofType:#"wds"];
NSData* data_ = [NSData dataWithContentsOfFile:sourcePath_
options:NSDataReadingMappedIfSafe error:&error];
dataSource_ = [NSKeyedUnarchiver unarchiveObjectWithData:data_];
The returned NSData object is empty. I checked the path of the NSData-File inside the bundle and it's correct. I guess that it's the problem that the file was created on OS X and that I want to deserialize it on iOS.
Is there a way to do this? Or do I have to write my own serialization class or use any third-party?

Related

Saving images to Main Bundle and then loading them into HTML works on Simulator, but not on real Device?

I'm trying to preload the image tags from an html string in order to load them when the device is offline. Basically, I strip the source url from all the <img>tags, clean the url to have a clean filename, then download the image.
__block NSString *imageName = [[NSString alloc]init];
//Get the string after HTTP://
NSArray *nohttp = [actualUrl componentsSeparatedByString:#"//"];
imageName = [nohttp objectAtIndex:1];
//Clean any /.:
imageName = [imageName stringByReplacingOccurrencesOfString:#"/" withString:#""];
imageName = [imageName stringByReplacingOccurrencesOfString:#"." withString:#""];
imageName = [imageName stringByReplacingOccurrencesOfString:#":" withString:#""];
//Add .png at the end as we will be saving it as a PNG
imageName = [NSString stringWithFormat:#"%#.png", imageName];
//change the source url to the new filename of the image so the WebView will load it from the main bundle
html = [html stringByReplacingOccurrencesOfString:actualUrl withString:imageName];
//save the image to the main bundle
NSString *pathString = [NSString stringWithFormat:#"%#/%#",[[NSBundle mainBundle]bundlePath], imageName];
//this just checks if the image already exists
BOOL test = [[NSFileManager defaultManager] fileExistsAtPath:pathString];
if (!test){
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul); dispatch_async(queue, ^(void) {
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:actualUrl]];
UIImage* image = [[UIImage alloc] initWithData:imageData];
NSData *imageData2 = UIImagePNGRepresentation(image);
[imageData2 writeToFile:pathString atomically:YES];
});
}
Then after I load the html string into the UIWebView, it works perfectly on the simulator, but on the device the images just aren't loaded. Why?
NSURL *baseUrl = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#",[[NSBundle mainBundle]bundlePath]]];
[self.webView loadHTMLString:self.htmlPage baseURL:baseUrl];
Any suggestions, thoughts? The images download fine on the iOS device/simulator but aren't loaded in the WebView of the real device. It works perfectly for the simulator.
That is correct.
On iOS an App's bundle is read-only. Any attempts to save changes into your bundle will fail on an iOS device.
On Mac OS the bundle is not read-only, but you should still treat it as read-only. Modifying your app's bundle is a bad idea. If the user updates their app from the app store, restores from a backup, etc, then changes you save to the bundle will be lost, even on Mac OS.
The simulator runs under Mac OS, and is built against Mac OS frameworks and the Mac file system.
There are a fair number of differences between the sim and running on a device. This is one.
Another example: The iOS file system is always case-senstive. The simulator, which runs on Mac OS, is not case-sensitive by default. (Mac OS can read from volumes running different file systems. The default file system is not case sensitive, but you can set it up to be case-sensitive.)
The file "Foo.txt" is a different file than the file "foo.txt". They can both exist in the same directory. If your file is called "Foo.txt" and you try to load it with the string "foo.txt" it will fail on an iOS device, but work on Mac OS.
As a result, you should always test your apps on an actual device. Don't assume that if something works correctly on the sim that it's correct for an iOS device. It may not be.

iOS: Some files don't open

I am attempting to load image files as an NSString, but all of them come up nil using this code:
NSString *path = [[NSBundle mainBundle] pathForResource:[NSString stringWithUTF8String:name.data()] ofType:nil];
NSString *da = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
I am able to load many files, but all JPEG and PNG files fail for some reason. I thought it might have something to do with encoding so I switched it to usedEncoding, but it still didn't work.
What am I missing?
EDIT:
I have been making an iOS/Android cross platform OpenGL graphics library in C++. Everything works except texture loading. Any file loading from disk goes through one function that is abstracted between systems. I need the image file in an STL string, so that I can pass it to an image parsing library to get the raw pixel data.
I just think that it's reduculous that the function I have can open any file except images.
If you run your code, passing an NSError instance instead of nil,
NSError *error = nil;
NSString *string = [NSString stringWithContentsOfFile:filePath
encoding:NSUTF8StringEncoding
error:&error];
you will see that stringWithContentsOfFile cannot open the image file, returning nil and the error given is:
Error Domain=NSCocoaErrorDomain Code=261 "The operation couldn’t be completed. (Cocoa error 261.)"...
Cocoa error 261 is NSFileReadInapplicableStringEncodingError which means the encoding of the file is different from the one you are passing (NSUTF8StringEncoding). But I have tried with the other encodings, and none works for PNG files.
You can still achieve what you want by loading the file as a UIImage and then converting the UIImage into a Base64 string.
Since iOS 7, this is easier because you can use the built in method base64EncodedStringWithOptions:
// Load the image and convert it to NSData
UIImage *image = [UIImage imageNamed:#"yourImageName"];
NSData *imageData = UIImagePNGRepresentation(image);
// You can use the equivalent UIImageJPEGRepresentation() for JPEG images
// Convert NSData to a Base64 NSString
NSString *base64ImageString = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
Previous to iOS 7, you can do the exact same thing but you will have to implement your own Base64 encoding method (Or import any of the many already available, eg. nicklockwood/Base64).

Xcode 6 keeps renaming my app's directory in iOS8 simulator after each run.

I'm running Xcode 6 Beta 5 but this has been happening since the first beta. My app's directory in the simulator keeps being renamed after each run. It took me a while to figure this out. I'm using this to get the doc's dir reference.
NSString *folder = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES) lastObject];
NSLog(#"Documents Dir: %#",folder);
Now for example on the first run it'll be:
/Users/Joey/Library/Developer/CoreSimulator/Devices/5B9930EE-A9B4-4B36-BABB-AA864ACAF2DE/data/Containers/Data/Application/4B10C2E4-A5C3-4C64-93B1-4069FCCB9C46/Documents
Second run now it's:
/Users/Joey/Library/Developer/CoreSimulator/Devices/5B9930EE-A9B4-4B36-BABB-AA864ACAF2DE/data/Containers/Data/Application/7E9EB62D-115A-4092-AD23-CB6BA3E5E10F/Documents
Third run:
/Users/Joey/Library/Developer/CoreSimulator/Devices/5B9930EE-A9B4-4B36-BABB-AA864ACAF2DE/data/Containers/Data/Application/EC8F41E8-52ED-4B10-9808-B3ACC46FC6AA/Documents
This is wreaking havoc with my app because it stores path references for certain files within the app. It's not that my NSLog statement is returning incorrect results, I verified this is what happening in Finder. It's changing the name every time. Has anyone seen this happen? Is this a "feature" that I'm misunderstanding?
Turns out Xcode 6 does in fact change the app's UUID every run, and I'm in the wrong for storing absolute paths.
USE SIMPHOLDERS
I used this app on Xcode 5 opens the Documents folder, for the currently running app in the simulator, in Finder.
http://simpholders.com/
not ready for Xcode 6 yet (as of sep 24 2014) but saves all this hassle.
In Xcode 6 / iOS8 The bundle is now separate from the data./ The application GUID is regenerated between runs in Xcode (not sure why)
DOCUMENTS DIR:/Users/gbxc/Library/Developer/CoreSimulator/Devices/AC79941F-EC56-495E-A077-773EEE882732/data/Containers/Data/Application/C220D351-0BE7-46BA-B35E-D16646C61A3F/Documents
mainBundlePath_:/Users/gbxc/Library/Developer/CoreSimulator/Devices/AC79941F-EC56-495E-A077-773EEE882732/data/Containers/Bundle/Application/12200D1D-9B67-408B-BCF7-38206CBE0940/myappname.app/BLANK_BLOG_SCALED.jpg
1. FIND THE DEVICES FOLDER in SIMULATOR
/Users/gbxc/Library/Developer/CoreSimulator/Devices/
open each /device.plist to see which GUID is which device in XCode - I think this is static
3. FIND THE DEVICE you're running on iPad 2 - I think this is static
/Devices/AC79941F-EC56-495E-A077-773EEE882732
4. Find your application /Documents folder
/AC79941F-EC56-495E-A077-773EEE882732/data/Containers/Data/Application/C220D351-0BE7-46BA-B35E-D16646C61A3F/Documents
BEWARE the GUID C220D351-0BE7-46BA-B35E-D16646C61A3F is regenerated everytime the app is run in XCode 6
NSArray *paths_ = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
if(paths_){
_docsDir = [paths_ firstObject];
DebugLog(#"DOCUMENTS DIR:%#",_docsDir);
}else{
ErrorLog(#"paths_ is nil - cant get Documents directory");
}
MAIN BUNDLE path
NSString *mainBundlePath_ = [[NSBundle mainBundle] pathForResource:#"someimageinyourbundle" ofType:#"jpg"];
/AC79941F-EC56-495E-A077-773EEE882732/data/Containers/Bundle/Application/12200D1D-9B67-408B-BCF7-38206CBE0940/clarksonsiq.app/BLANK_BLOG_SCALED.jpg
NEVER CACHE THE PATH to /Documents between runs it will change.
I was serializing it to a plist and couldnt figure out why they kept disappearing
The GUID above /Documents keeps changing between runs but if you have /Documents open in Finder the folder stays open.
https://devforums.apple.com/thread/235911?tstart=0
https://devforums.apple.com/thread/238754?tstart=0
Free Solution
Use Open Source Library OpenSim. OpenSim is an open source alternative for SimPholders, written in Swift.
Paid Solution
Use SimPholder application to know current application location.
For xcode 6.0 >
Download SimPholder 2.0 alpha 2
For xcode 5.1 <
Download SimPholders 1.5
I can confirm that this is Xcode 6 related not iOS 8.
I have two development machines. On one of them I have Xcode 5. I was working all the time on that machine and my URL's were fine (photo app, photos are visible).
Yesterday I checked in form git my source on a machine with Xcode 6. I noticed that my photos are not visible any more, only photos that are created during that app session.
After little debugging, I realized that file:///var/mobile/Applications/B6A6BAEF-C90C-4A2A-93DB-E6700B88971F/Documents/ is changing on every app run.
All that time I am working with iOS 7 device.
I am going to check once more on a machine with Xcode 5 to confirm when I get my hands on it.
You need to to save only path inside DocumentDirectory(directory/file name), and add it to the DocumentDirectory every time you load the file...
-(void)saveImage:(UIImage *)image{
NSData *pngData = UIImagePNGRepresentation(image);
NSString *pathInDocumentDirectory = [APP_DocumentDirectory stringByAppendingPathComponent:PROFILE_IMAGE_NAME];
NSString *filePath = [self documentsPathForFileName:pathInDocumentDirectory];
//Save pic file path - DirName/Filename.png
[XYZPreferencesHelper setUserImageFilePath:pathInDocumentDirectory];
//Write the file
[[NSFileManager defaultManager] createFileAtPath:filePath contents:pngData attributes:nil];
}
-(void)loadSavedUserPicture{
//Load saved DirName/Filename.png
NSString *pathInDocumentDirectory = [XYZPreferencesHelper getUserImageFilePath];
if (pathInDocumentDirectory != nil){
//Full path with new app Document Directory
NSString *filePath = [self documentsPathForFileName:pathInDocumentDirectory];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]){
NSData *pngData = [NSData dataWithContentsOfFile:filePath];
UIImage *image = [UIImage imageWithData:pngData];
if (image != nil){
userPicImageView.image = image;
}
}
}
}
- (NSString *)documentsPathForFileName:(NSString *)name
{
NSString *documentsPath = [self createRestcallDirectoryIfNotExist];
return [documentsPath stringByAppendingPathComponent:name];
}
-(NSString *)createRestcallDirectoryIfNotExist{
NSString *path;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
path = [documentsPath stringByAppendingPathComponent:APP_DocumentDirectory];
NSError *error;
if (![[NSFileManager defaultManager] fileExistsAtPath:path]) //Does directory already exist?
{
if (![[NSFileManager defaultManager] createDirectoryAtPath:path
withIntermediateDirectories:NO
attributes:nil
error:&error])
{
NSLog(#"Create directory error: %#", error);
}
}
return documentsPath;
}
Because app's UUID changes and not reliable 
so we should not store urls instead we should store just file names and reconstruct url at runtime , on update/reinstall iOS creates new home directory, stores app bundle in it and copies documents files so url changes


NSKeyedArchiver not persisting data

So, my app queries an Amazon Dynamo DB database and retrieves a few kilobytes worth of data. What I want the app to do is download everything the first time, and then every time after, just download a timestamp to see if it has the most recent version of the data. So that I only have to download the data every once in a while, I'm trying to use NSKeyedArchiver to archive the array that I'm downloading. I have tried this three different ways, and none of them work on an iPhone, although two of them work on the simulator.
[NSKeyedArchiver archiveRootObject:self.dataArray toFile:#"dataArray.archive"];
This does not work on the simulator nor the actual iphone. The result of this method is NO.
The next thing I used was the full path:
[NSKeyedArchiver archiveRootObject:self.dataArray toFile:#"Users/Corey/Desktop/.../dataArray.archive"];
And this worked on the simulator, but not on the iPhone. My guess was that when compiled, the filesystem looks different (and obviously doesn't have the same path). So next I tried:
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"dataArray" ofType:#".archive"];
[NSKeyedArchiver archiveRootObject:self.dataArray toFile:filePath];
Once again, this works on the simulator but fails on the iphone. I have confirmed that all of the data is in self.dataArray before writing to the archive, and confirmed that the array is nil after writing back to the archive (in the iphone version). Any ideas what's going on? Is there a better way to do the filepath?
This is what I tracked down:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent: #"dataArray.archive"];
[NSKeyedArchiver archiveRootObject:your_object toFile:filePath];
and it worked perfectly on both the simulator and the iPhone!
[NSKeyedArchiver archiveRootObject:self.dataArray toFile:#"dataArray.archive"];
You have to provide a full path.
[NSKeyedArchiver archiveRootObject:self.dataArray toFile:#"Users/Corey/Desktop/.../dataArray.archive"];
That is not a full path. A full path begins with / and does not have /../ anywhere.
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"dataArray" ofType:#".archive"];
You do not have permission to write inside the mainBundle, it is read only.
Also, in general you shouldn't use file paths, you should use URLs. Some APIs (including this one) requires a path but URLs are the recommended approach these days.
Here's the proper way to write the file to disk:
NSURL *applicationSupportUrl = [[NSFileManager defaultManager] URLsForDirectory:NSApplicationSupportDirectory inDomains:NSUserDomainMask][0];
applicationSupportUrl = [applicationSupportUrl URLByAppendingPathComponent:#"My App"]; // replace with your app name
if (![applicationSupportUrl checkResourceIsReachableAndReturnError:NULL]) {
[[NSFileManager defaultManager] createDirectoryAtURL:applicationSupportUrl withIntermediateDirectories:YES attributes:#{} error:NULL];
}
NSURL *archiveUrl = [applicationSupportUrl URLByAppendingPathComponent:#"foo.archive"];
[NSKeyedArchiver archiveRootObject:self.dataArray toFile:archiveUrl.path];

Loading image from folder using NSBundle and plist

Trying to Display the load the image from the folder present on MAC desktop using path like (/Users/sai/Desktop/images/aaa.jpg) Which is created in plist file called Data.plist at item0.
As im using NSBundle it is diaplying the image path but not loading the image from the desktop .I have done a lots of research still couldn't find the solution .Plz help me .Here is the code
NSString *path=[[NSBundle mainBundle]pathForResource:#"Data" ofType:#"plist"];
NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:path];
NSString *errorDesc = nil;
NSPropertyListFormat format;
NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization propertyListFromData:plistXML mutabilityOption:NSPropertyListMutableContainersAndLeaves format:&format errorDescription:&errorDesc];
NSArray *array=[NSArray arrayWithArray:[temp objectForKey:#"images"]];
NSString *object=[array objectAtIndex:0];
NSLog(#"object at index i %#",[object lastPathComponent]);
NSString *image=[object lastPathComponent];
mImageView.image=[UIImage imageNamed:image];
[self.view addSubview:mImageView];
Here is the screen shot of Data.plist
Simple and Short answer : It is not Possible to get image from MAC desktop, So please it better to stop fighting with it :)
It is different for mobile (iPhone application) and desktop (mac application), but why you want to do this ?? you know that your iOS application install in Apple iPhone ???? if your application is related to iOS ? then how you connect it to MAC OS ??
Best and simple way is put this image in Application Bundle or your Application's document directory and get it.

Resources