trouble accessing files loaded into project - xcode

I've added a bunch of files to my swift project folder like so:
I need to access these files at a certain point in the project for two purposes:
Use the name of each file to populate Categories (ie. Age, Alone, Amazing...)
Access the data within the files to populate each Category items page
I've implemented this code in the viewDidLoad of my class to access and iterate through the files
//get categories
let fileManager = NSFileManager.defaultManager()
let directoryPath = NSHomeDirectory() + "/Categories"
let enumerator:NSDirectoryEnumerator = fileManager.enumeratorAtPath(directoryPath)!
while let element = enumerator.nextObject() as? String {
println(String(element))
}
This does not work and produces the error fatal error: unexpectedly found nil while unwrapping an Optional value on the line let enumerator:NSDirectoryEnumerator = fileManager.enumeratorAtPath(directoryPath)!. I suspect (and correct me if I'm wrong), that it is accessing the applications internal file structure and as a result cannot find the files specified. As I am new to IOS development, my general understanding of how this works is nebulous at best.
So How exactly do I access files I've added the project in the way I've shown in the image, so as to iterate through and get the data I'm looking for
EDIT
So I've changed the structure to make the Categories folder an actual folder like so:
I'm currently trying to use NSBundle to access the application route, however I am not sure how to do that. Any guidance would be appreciated.

The problem is that xcode's project navigator folders are not actual folders in the disk. So this:
let directoryPath = NSHomeDirectory() + "/Categories"
does not exist in your hdd. If you want this folder you have to navigate to your projects folder on your hdd, create it manually and add the files you want in it.
You can refer to a file and read it like this:
let htmFile = NSBundle.mainBundle().pathForResource("aboutText", ofType: "html")
let htmlString = NSString(contentsOfFile: htmFile!, encoding: NSUTF8StringEncoding, error: nil)
for json you can get a dictionary with
let jsonFile = NSBundle.mainBundle().pathForResource("aboutText", ofType: "json")
let dict = NSDictionary(contentsOfFile: jsonFile)

Related

Access the Android Special Folder Path by using Environment

I want to save my logs to a folder which I can access with windows explorer. For example I want to create my log in the following path
This PC\Galaxy A5 (2017)\Phone\Android\data\MyApp\files
So I tried to use Environment variables... I get such as
/data/user/...
But here i cannot see the file what I created (using code I can access the path but I want to see in the explorer).
how I can create a path like above with code?
When I tried this code
var finalPath2 = Android.OS.Environment.GetExternalStoragePublicDirectory
(Android.OS.Environment.DataDirectory.AbsolutePath);
I get the path "/storage/emulated/0/data"
and
If i use the code
var logDirectory =Path.Combine(System.Environment.GetFolderPath
(System.Environment.SpecialFolder.ApplicationData),"logs");
I get the following path like:
/data/user/0/MyApp/files/.config/logs
and
var logDirectory =Path.Combine(System.Environment.GetFolderPath
(System.Environment.SpecialFolder.MyDocuments),"logs");
"/data/user/0/IM.OneApp.Presentation.Android/files/logs"
but unfortunately I cannot access this folder by explorer....
This PC\Galaxy A5 (2017)\Phone\Android\data\MyApp\files
So how to find out this path in c# by using environments?
Update:
when I give the following path hardcoded, it creates the file where I want..
logDirectory = "/storage/emulated/0/Android/data/MyApp/files/logs";
is there any environment to create this path? I can combine 2 environments and do some string processing in order to create this path. But maybe there is an easier way?
You are looking for the root of GetExternalFilesDir, just pass a null:
Example:
var externalAppPathNoSec = GetExternalFilesDir(string.Empty).Path;
Note: This is a Context-based instance method, you can access it via the Android application context, an Activity, etc... (see the link below to the Android Context docs)
Shared storage may not always be available, since removable media can be ejected by the user. Media state can be checked using Environment.getExternalStorageState(File).
There is no security enforced with these files. For example, any application holding Manifest.permission.WRITE_EXTERNAL_STORAGE can write to these files.
re: https://developer.android.com/reference/android/content/Context#getExternalFilesDir(java.lang.String)
string docFolder = Path.Combine(System.Environment.GetFolderPath
(System.Environment.SpecialFolder.MyDocuments), "logs");
string libFolder = Path.Combine(docFolder, "/storage/emulated/0/Android/data/MyApp/files/logs");
if (!Directory.Exists(libFolder))
{
Directory.CreateDirectory(libFolder);
}
string destinationDatabasePath = Path.Combine(libFolder, "temp.db3");
db.Backup( destinationDatabasePath, "main");

How do I programmatically access the Settings.bundle?

Scenario:
Settings.bundle within the host application.
Goal:
To access the data within the settings.bundle.
Modus Operandi:
To dump the settings data into a dictionary for in-program access.
Here's my first attempt. I tried accessing the path, then the bundle. Both didn't work:
let path = NSBundle.mainBundle().pathForResource("Settings", ofType: "bundle")
let myBundle = NSBundle(path: path!)
let myData = NSDictionary(contentsOfFile:path!)
What's the correct syntax of collecting data from the Settings.bundle (which contains the root.plist)?
You can access the saved values via NSUserDefaults.
For example if you want to get the previously set value ("bar") from the setting named as "foo", then the code to get it is:
let valueOfFoo = NSUserDefaults.standardUserDefaults().valueForKey("foo")
In this case the content of valueOfFoo variable will be "bar".
Note: this returns an Optional

Saving a PFFile into cloud - where did it go?

According the the Files section of the Parse documentation, to save a PFFile, we should follow these steps:
Create the PFFile
Save the PFFile to the cloud
After saving completes, associate the PFFile with a PFObject
I have troubles visualizing step #2. Here's the example code they provided, which I tried to run myself:
//1. Creating the PFFile
let str = "Working with Parse is great!"
let data = str.dataUsingEncoding(NSUTF8StringEncoding)!
let file = PFFile(name: "resume.txt", data: data)
//2. Saving the PFFile
file.saveInBackgroundWithBlock { succeeded, error in
if error != nil {
println(error)
}
if succeeded {
println("succeeded saving PFFile to cloud")
}
}
When I ran the code, the file succeeded in saving. But upon checking in my Parse app database, I see nothing that indicates the object is saved.
What is the point of step #2?
Step #2 doesn't result in anything visible in the Parse database browser. It uploads the file, but nothing references it so it's not visible. You need to associate it with an object, and then it'll be visible via the field you save it in within that object.
Also, if you look in the Settings -> General area in Parse.com for your app, near the bottom of the main pane, you'll see a link for "Clean Up Files". I believe this looks at all the files that have been uploaded, but are not associated with any objects in your database, and removes them.

How to download a jpg from web to project folder in MVC3?

Hello everyone I would like to ask How can I download .jpg file from web to my project's folder which I have created "uploads" ?
I'm trying to downlaod youtube thumbnail image to my" uploads" folder.
My controller:
var fileName = Path.GetFileName(http://img.youtube.com/vi/RUgd_GDPhYk/1.jpg);
var path = Path.Combine(Server.MapPath("~/uploads/"), fileName);
file.SaveAs(path);
Take a look at System.Net.WebClient, a .NET class which allows you to make requests for resources via HTTP.
http://msdn.microsoft.com/en-us/library/system.net.webclient(v=vs.100).aspx
Checked example provided.
var client = new System.Net.WebClient();
var uri = "http://img.youtube.com/vi/RUgd_GDPhYk/1.jpg";
// Here, we're just using the same filename as the resource we're after.
// You may wish to change this to include extra stuff because you'll
// inevitably run into a naming clash - especially with stuff like 1.jpg
var targetFilename = Path.GetFileName(uri);
client.DownloadFile(uri,
Path.Combine(Server.MapPath("~/uploads"), targetFilename));

AU Preset (.aupreset) resource path issue in iOS LoadPresetDemo sample code

I've been working with the iOS LoadPresetDemo sample code - if loads AUPreset files to configure different types of samplers (pretty cool) - and have run into a question/issue.
The demo code runs fine but when I try to reuse the .aupreset files in test project built from scratch, the Trombone.aupreset doesn't work. Digging into it, I noticed what seems like oddness with the audio sample paths in the .aupreset file.
The paths in the plist (images below) point to:
file://localhost//Library/Audio/Sounds/Tbone/1a%23.caf
but that is not the correct path - according to the project directory structure. There are no "Library/Audio" directories - virtual or real. So I'm confused. The Apple demo works fine but my from scratch project does not (get error -43 when trying to load the samples). The code that loads the samples (at bottom) is not doing anything to relativize the paths at runtime.
Does anyone see what I am misunderstanding here? - Thanks!
// Load a synthesizer preset file and apply it to the Sampler unit
- (OSStatus) loadSynthFromPresetURL: (NSURL *) presetURL {
CFDataRef propertyResourceData = 0;
Boolean status;
SInt32 errorCode = 0;
OSStatus result = noErr;
// Read from the URL and convert into a CFData chunk
status = CFURLCreateDataAndPropertiesFromResource (
kCFAllocatorDefault,
(__bridge CFURLRef) presetURL,
&propertyResourceData,
NULL,
NULL,
&errorCode
);
NSAssert (status == YES && propertyResourceData != 0, #"Unable to create data and properties from a preset. Error code: %d '%.4s'", (int) errorCode, (const char *)&errorCode);
// Convert the data object into a property list
CFPropertyListRef presetPropertyList = 0;
CFPropertyListFormat dataFormat = 0;
CFErrorRef errorRef = 0;
presetPropertyList = CFPropertyListCreateWithData (
kCFAllocatorDefault,
propertyResourceData,
kCFPropertyListImmutable,
&dataFormat,
&errorRef
);
// Set the class info property for the Sampler unit using the property list as the value.
if (presetPropertyList != 0) {
result = AudioUnitSetProperty(
self.samplerUnit,
kAudioUnitProperty_ClassInfo,
kAudioUnitScope_Global,
0,
&presetPropertyList,
sizeof(CFPropertyListRef)
);
CFRelease(presetPropertyList);
}
if (errorRef) CFRelease(errorRef);
CFRelease (propertyResourceData);
return result;
}
I had the same Problem and after 2 hours of comparing the "load preset"-Demo with my code I found the solution:
When adding the sound-folder check the options:
Copy items
Create folder references for any added folders -- and the added folders will be blue like in the "load preset"-demo-project!
The following is from Apple Technical Note TN2283 and discusses the paths issue that was initially asked about. You will obviously need to have the Sounds Folder, your assets and preset file part of your bundle.
Technical Note TN2283 AUSampler - Loading Instruments Excerpt
When the AUSampler attempts to load audio files via the paths provided in the external file refs portion of an .aupreset file or a set of individual file URLs, it will use the following rules to resolve each path:
If the audio file is found at the original path, it is loaded.
If the audio file is NOT found, the AUSampler looks to see if a path includes a portion matching "/Sounds/", "/Sampler Files/" or "/Apple Loops/" in that order.
If the path DOES NOT include one of the listed sub-paths, an error is returned.
If the path DOES include one of the listed sub-paths, the portion of the path preceding the sub-path is removed and the following directory location constants are substituted in the following order:
Bundle Directory
NSLibraryDirectory
NSDocumentDirectory
NSDownloadsDirectory
For example, in an iOS application if the original path was "/Users/geddy/Library/Audio/Sounds/MyFavoriteHeadacheSound.caf" and this path was not found, the AUSampler would then search for the audio file in the following four places:
<Bundle_Directory>/Sounds/MyFavoriteHeadacheSound.caf
<NSLibraryDirectory>/Sounds/MyFavoriteHeadacheSound.caf
<NSDocumentDirectory>/Sounds/MyFavoriteHeadacheSound.caf
<NSDownloadsDirectory>/Sounds/MyFavoriteHeadacheSound.caf
Therefore using the above example, if you were moving a preset created on the Desktop to an iOS application you could simply place the MyFavoriteHeadacheSound.caf file in a folder called "Sounds" within your application bundle and the AUSampler will find the audio file referenced by the preset.
You need to add both presets to your target so that they are part of the bundle:
That's what the line:
NSURL *presetURL = [[NSURL alloc] initFileURLWithPath:[[NSBundle mainBundle] pathForResource:#"Trombone" ofType:#"aupreset"]];
says.
Also you may want to have a look at Referencing External Audio Files at the bottom of the page.

Resources