How to access a computer file on a phone - ios

I am using
let data = try?
NSString(contentsOfFile: "/Users/BenA**** 1/Desktop/textFile.txt",
encoding: String.Encoding.utf8.rawValue)
to access a file on my computer. When I test put the app on my phone, it obviously didn't work because it didn't have access to the file. How could I put this file on my phone and be able to access it from there? Thanks.

Include your "textFile.txt" in main bundle by drag and drop file in to xcode project, then access it by
class testViewController: UIViewController{
var data:String = ""
override func viewDidLoad() {
super.viewDidLoad()
let path = NSBundle.mainBundle().pathForResource("textFile", ofType: "txt")
data = try? NSString(contentsOfFile: path!, encoding: ENCODING)
}}
Try this way to access 'data' in rest of code.
Hope this help.

To simulate the behavior of iOS enable the sandbox on macOS.
Now you can access files only in the container of the app.
Nevertheless the predefined folders like Documents, Library etc. still exist.
To have access to that directories there a method of NSFileManager. For example one of the most important directories in iOS is the Documents directory.
let documentsFolderURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomain: .UserDomainMask).first!
You have to use that method each time you need to get the URL of that particular directory because for security reasons the absolute path will change.

Related

is the temporaryDirectory of FileManager automatically removed by iOS? if so when?

I am adding an option in my App to backup everything to a file.
For that, I am serializing all my objects to a dictionary that I save in a single file in the path provided by FileManager.default.temporaryDirectory. Then I ask the user for a path to save this file using a UIDocumentPickerViewController.
Everything works fine, but I wonder what happens with the temporal file that I created in the temporaryDirectory. Is this automatically removed by the operating system? should I take care of removing it by myself?
This is how I get the path of the temporary directory for my file:
private var exportURL: URL {
let documentURL = FileManager.default.temporaryDirectory
let fileName = "archive"
let filePath = "\(fileName).backup"
return documentURL.appendingPathComponent(filePath)
}

Get Reference to SceneKit Catalog Swift

I must be missing something simple - I'm trying to iterate through the
files in an .scnassets folder but can't seem to get a reference to the
folder/catalog.
Here's the organizer:
Models.scnassets contains one file. I tried this:
let fileManager = FileManager.default
let urls = fileManager.urls(for: .documentDirectory, in: .userDomainMask)
let docsURL = urls.first
let assetFolderPath = docsURL?.appendingPathComponent("Models.scnassets").path
And I tried this and several other variants:
let modelPathString = "ARAds/Models.scnassets"
Then I attempted to count the files with both of the above paths:
do {
let modelPathDirectoryFiles = try fileManager.contentsOfDirectory(atPath: assetFolderPath!)
//or modelPathString
print(modelPathDirectoryFiles.count)
} catch {
print("error getting list of files")
}
I get the error message in all cases.
I assume there must be some special way to get a reference to a SceneKit
Catalog but I have not been able to find that in the Apple docs nor SO.
Any guidance would be appreciated. iOS 11.4 Xcode 10.0
Looking at your code, the first thing I see, is that you are referencing the Documents Directory which isn't actually where your folder is.
The Documents Directory is a folder on your actual device where you might save user data or other files which can be accessed at a latter date (for example via iTunes Sharing).
If you move your Models.scnassets folder under the yellow ArAds folder you should be able to access your content like so:
let myModelToLocate = SCNScene(named: "Models.scnassets/Phone_01.scn")
Hope it helps...
You've pointed me in a better direction, but I can already get the scn and make a node if I know the name. What I really want to do is populate a tableview with the options that are available - so I need to find the current list of scene files.
I think this will work:
let subdir = Bundle.main.resourceURL!.appendingPathComponent("Models.scnassets").path
do {
let modelPathDirectoryFiles = try fileManager.contentsOfDirectory(atPath: subdir)
print(modelPathDirectoryFiles.count) //this works
//then do my thing with the array
} catch {
print("error getting list of files")
}
This seems to work, whether I move the folder or not.

Swift 3 - WKWebView Load Local HTML not loading resource files

I was download my website from online to store in xcode project with a sub-folder and want to run in WKWebView locally. I found the webview loaded webpage miss all CSS/JS/Images resources. I search around the internet and still not working. Is webpage inside relative url incorrect or my code to get the Main Bundle location problem? Anyone can help. Thanks.
Xcode Project Structure
HTML Page Contents Sample
I wrote this code to load WKWebView
let htmlFile = Bundle.main.path(forResource: "provisiontech", ofType: "htm")
let html = try? String(contentsOfFile: htmlFile!, encoding: String.Encoding.utf8)
let baseURL = Bundle.main.resourceURL!.appendingPathComponent("pvtc")
webView.loadHTMLString(html!, baseURL: baseURL)
The webview has no access to the resource folder. You should use loadFileURL(_:allowingReadAccessTo:) instead. Preloading the data is not neccessary, e.g.:
let url = Bundle.main.url(forResource: "provisiontech", ofType: "htm")
webView.loadFileURL(url, allowingReadAccessTo:
Bundle.main.resourceURL!.appendingPathComponent("pvtc"))
Edit: If the webview still cannot access the resources, you should consider whether putting the page and all resources into the same folder.

How to find Apple App Group shared directory

We are currently developing an iOS10 app, including "Messages Extension".
To share CoreDatas persistant store.sqlite inbetween App and Extension, we are using a shared "Apple App Group" directory, which is working fine.
Now we have to get our hands on the store for debug reasons and are unable to find the directory. The Apps container directories are completely empty, which makes sense. But how to download our database? Do we have to somehow copy it programmatically to a reachable place?
To sum it up:
We already use CoreData which stores model.sqlite in our shared directory.
Everything is up and running.
What we want to archive is to download the database to our computer.
Without a shared directory we can simply download the App container from the device, using Xcode->Devices. But as we do use a shared directory, the .sqlite database is not within the container.
Question:
How can we download the .sqlite database from the device to our computer?
EDIT on 2018-10-12: Updated code for Swift 4.x (Xcode 10). (Older version retained for reference.)
In Swift 4.x:
let sharedContainerURL :URL? = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.etc.etc")
// replace "group.etc.etc" above with your App Group's identifier
NSLog("sharedContainerURL = \(String(describing: sharedContainerURL))")
if let sourceURL :URL = sharedContainerURL?.appendingPathComponent("store.sqlite") {
if let destinationURL :URL = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("copyOfStore.sqlite") {
try! FileManager().copyItem(at: sourceURL, to: destinationURL)
}
}
In older version of Swift (probably Swift 2.x):
let sharedContainerURL :NSURL? = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier("group.etc.etc") // replace "group.etc.etc" with your App Group's identifier
NSLog("sharedContainerURL = \(sharedContainerURL)")
if let sourceURL :NSURL = sharedContainerURL?.URLByAppendingPathComponent("store.sqlite")
{
if let destinationURL :NSURL = NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0].URLByAppendingPathComponent("copyOfStore.sqlite")
{
try! NSFileManager().copyItemAtURL(sourceURL, toURL: destinationURL)
}
}
Something like the above will get a file from the app group's shared container to the app's Documents directory. From there, you could use Xcode > Window > Devices to get it to your computer.
You could also use iTunes file sharing to retrieve the file from the app's Documents directory after setting UIFileSharingEnabled to YES in the Info.plist file, but bear in mind that this will expose the directory's contents to the user as well. Should be okay for development/debugging purposes, though.

Does using a path from system, while calling a file, cause crashes?

I've a text file that stores my app's data for me.
If I use system path (/Users/username/Desktop/ProjectFile/data.txt), can it cause errors when application compiled into .ipa file?
open the file in your project, and check the target membership, as shown in following image. If target membership icon is checked for your corresponding target, then it will not make any problem during compilation(creating ipa). But if target membership is unchecked for your target build, then it will make the problem.
Using path form system like in the question causes crash when tested on a real iOS device.
Instead of using system path, using the code below will be more advantageous. It prevents crashes on real device.
let path = NSBundle.mainBundle().pathForResource("file", ofType: "txt")
let fileMgr = NSFileManager.defaultManager()
var array: [String] = []
if fileMgr.fileExistsAtPath(path!) {
do {
let text = try! String(contentsOfFile: path!, encoding: NSASCIIStringEncoding)
array = text.componentsSeparatedByString("|#|")
}
}

Resources