How to find Apple App Group shared directory - ios

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.

Related

Importing Documents from iMessage into App - Deleting temp files placed in "Inbox"

I have defined a UTI for a custom document format. I can export files from my app and append them to text messages, email, etc. I can import the files into my app by tapping on the document icon in iMessage. By tapping on the document icon, I have the option to copy to my app. That triggers a call in my AppDelegate to handle the incoming file.
What's bugging me is that the url for the incoming file is:
file:///private/var/mobile/Containers/Data/Application/21377C94-1C3C-4766-A62A-0116B369140C/Documents/Inbox/...
Whereas, when saving documents to the .documents directory, I use this URL:
file:///var/mobile/Containers/Data/Application/21377C94-1C3C-4766-A62A-0116B369140C/Documents/...
The difference being the /private/ and /Inbox/ path components.
Question: how can I purge the /private/.../Inbox/ path of the files that were copied to my app from iMessage? I noticed this when testing my app and when I tapped on the same document icon in iMessage it started generating file copies with the same name but adding -1, then -2, then -3 to the file name of the document from iMessage. It appears that copies are building up in that /private/.../Inbox/ path.
Is that something that gets flushed on its own or can I access that directory to remove those files? It's also annoying because based upon the filename, it appears to be a different file thus allowing multiple copies of the same file to be imported with a slightly different file name.
Ok, this took a fair amount of digging, but I'll post my solution that seems to work thus far in case anyone runs across the same problem.
let fileManager = FileManager.default
// get the URL for the "Inbox"
let tmpDirURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("Inbox")
// get all the files in the "Inbox" directory
let anythingThere = try? fileManager.contentsOfDirectory(at: tmpDirURL, includingPropertiesForKeys: nil)
if anythingThere?.count ?? 0 > 0 {
for eachURL in anythingThere! {
// for each url pointing to a file in that directory, get its path extension
let pathExtension = eachURL.pathExtension
// test to see if it's a UTI that you're interested in deleting
// in my case, the three "OCC" strings are the relevant UTI extensions
if pathExtension == "OCCrcf" || pathExtension == "OCCrdi" || pathExtension == "OCCsrf" {
// attempt to delete the temporary file that was copied to the
// "Inbox" directory from importing via email, iMessage, etc.
try fileManager.removeItem(at: eachURL)
}
}
}
If anyone has a more elegant solution, please respond as well. Thanks.

How do I get the temp directory in iOS using Swift? [duplicate]

My app has just been rejected by Apple because it was storing temporary or cache files in the documents directory. Right. Their rejection message states:
Temporary files used by your app should only be stored in the /tmp directory
I suppose it is that besides the Documents and Library in the Application's folder.
I am now trying to debug this issue in the iPhone Simulator, and when I use NSTemporaryDirectory(), the value I get in the Xcode debugger is /var/folders/yj/gnz1c7156c7d6d4fj429yms40000gn/T/tempzip.zip, and not /Users/me/Library/Application Support/iPhone Simulator/5.1/Applications/8F71AB72-598C-427A-A116-36833D3209F7/tmp/tempzip.zip.
So: is NSTemporaryDirectory() having a different behaviour using the iPhone Simulator, and, is it possible to track the application's temporary directory at debug time ?
iOS 9 or later • Swift 3 or later
let tmpDirURL = URL(fileURLWithPath: NSTemporaryDirectory())
iOS 10.0+Beta, macOS 10.12+, tvOS 10.0+Beta & watchOS 3.0+ • Xcode 8 • Swift 3 or later
let tmpDirURL = FileManager.default.temporaryDirectory
UPDATED 2016 ANSWER :
Data which is explicitly accepted by the user as personal, and potentially backuped in his/her iCloud space, should be written in user's "Documents" directory
Data that belongs and extends your application (an extension user can download for instance,...), but which is NOT in the bundle, should be written in a subfolder of "Application Support/" directory, having the title of your appID. It can also be the "Cache" directory.
Data with short-life time can be stored in the tmp directory of your application. In this case, use of NSTemporaryDirectory() is possible to get the "tmp" directory. Check this link for additional help.
Check this official iOS developement Apple page in section "Determining Where to Store Your App-Specific Files" for explanations.
Below are 3 functions in Swift designed to return NSURLs to these directories and make your like simpler.
Swift:
func GetDocumentsDirectory()->NSURL{
//returns User's "Documents" directory
//something like this on a real device : file:///private/var/mobile/Containers/Data/Application/APPID/Documents/
//something like this on the simulator : file:///Users/MACUSERID/Library/Developer/CoreSimulator/Devices/SIMDEVICEID/data/Containers/Data/Application/APPUUID/Documents/
let filemgr = NSFileManager.defaultManager()
let docsDirURL = try! filemgr.URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
return docsDirURL
}
func GetApplicationSupportDirectory()->NSURL{
//returns Application's support directory
//something like this on a real device : file:///private/var/mobile/Containers/Data/Application/APPID/Library/Application%20Support/YOURAPPBUNDLEID/
//something like this on the simulator : file:///Users/MACUSERID/Library/Developer/CoreSimulator/Devices/SIMDEVICEID/data/Containers/Data/Application/APPUUID/Library/Application%20Support/YOURAPPBUNDLEID/
let AllDirectories : [NSURL]
var ApplicationSupportDirectory : NSURL=NSURL.init()
var ApplicationDirectory : NSURL=NSURL.init()
AllDirectories=NSFileManager.defaultManager().URLsForDirectory(.ApplicationSupportDirectory, inDomains: .UserDomainMask)
if AllDirectories.count>=1{
ApplicationSupportDirectory=AllDirectories[0]
}
if !ApplicationSupportDirectory.isEqual(nil) {
ApplicationDirectory=ApplicationSupportDirectory.URLByAppendingPathComponent(NSBundle.mainBundle().bundleIdentifier!)
}
return ApplicationDirectory
}
func GetTemporaryDirectory()->NSURL{
//returns Application's temporary directory
//something like this on a real device : file:///private/var/mobile/Containers/Data/Application/APPID/tmp/
//something like this on the simulator : file:///Users/MACUSERID/Library/Developer/CoreSimulator/Devices/SIMDEVICEID/data/Containers/Data/Application/APPUUID/tmp/
return NSURL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
}
I have tested this on a real device, and it returned : "/private/var/mobile/Applications/C82383-EBD6-4F72-BC16-A865478D27/tmp/tempzip.zip"
So overall, using NSTemporaryDirectory() is the correct way of finding the path to the temporary directory, and that if you want to debug and view what is done within, you need to find it manually in the Finder if you are using the iPhone Simulator.
Check newer answer below (this one is deprecated)
According to the docs, you should avoid NSTemporaryDirectory() in favour of this approach
- (NSURL)URLForTemporaryFolder
{
// Get a parent folder, trying user folder (fails iOS) and falling back to AppSupport and Docs
NSURL *parentFolderURL = [NSURL URLForDirectory:NSUserDirectory domainMask:NSUserDomainMask];
if (!parentFolderURL) parentFolderURL = [NSURL URLForDirectory:NSApplicationSupportDirectory domainMask:NSUserDomainMask];
if (!parentFolderURL) parentFolderURL = [NSURL URLForDirectory:NSDocumentDirectory domainMask:NSUserDomainMask];
// Get the temp folder URL using approach outlined in the docs
NSURL *tmpURL = [[NSFileManager defaultManager]
URLForDirectory:NSItemReplacementDirectory
inDomain:NSUserDomainMask
appropriateForURL:parentFolderURL
create:YES
error:NULL];
return tmpURL;
}
Be aware that this creates a new unique temp folder each time you call it and it's up to you to clean it up.

Application ID of NSSearchPathForDirectoriesInDomains Changes per Simulator Run & Update App on Real Device

I'd like to persist images to user domain of iPhone so I write the following code.
let path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0]
print(path)
It shows like: /Users/xxx/Library/Developer/CoreSimulator/Devices/1312F880-6BDC-45D2-B3B3-4D2374313C67/data/Containers/Data/Application/A2850237-5E71-4373-81A6-B443032E1951/Documents/
In this case, Application ID is A2850237-5E71-4373-81A6-B443032E1951
And the problem is when I run on simulator again WITHOUT REMOVING THE APP, it shows like: /Users/xxx/Library/Developer/CoreSimulator/Devices/1312F880-6BDC-45D2-B3B3-4D2374313C67/data/Containers/Data/Application/1F9B5B0A-5A6C-4098-BF40-C978C60C93AF/Documents/
In this case, Application ID is 1F9B5B0A-5A6C-4098-BF40-C978C60C93AF
So there are Application ID difference between previous and current install although I just did update the app and didn't remove the app. Why it is caused and how to fix it?
It causes Xcode 7.2, 7.1, 7.0. And it causes with not only simulator install but also actual device install. So if iOS users update the app from app store, the Application ID will be changed and app sandbox will also be changed and finally users cannot refer their images.
Similar Situations:
Xcode 6.3 seems to change the path to the Documents directory per app run
xcode 6.2 create a new simulator path every time when run the app
Related Guidelines:
File System Basics
Thanks in advance.
EDIT
It seems I have to persist path as relative not absolute.
Application folder name changes every time i run in simulator [duplicate]
Xcode 6 keeps renaming my app's directory in iOS8 simulator after each run.
I'll try the approach and if I solved my problem, I'll update the question.
I have to persist path relative not absolute. And I also can salvage old run images by fetching with NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] + "persisted relative path".
A better solution is to save a bookmark data
https://developer.apple.com/library/ios/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/AccessingFilesandDirectories/AccessingFilesandDirectories.html
A bookmark is an opaque data structure, enclosed in an NSData object,
that describes the location of a file. Whereas path- and file
reference URLs are potentially fragile between launches of your app, a
bookmark can usually be used to re-create a URL to a file even in
cases where the file was moved or renamed
First you must use NSURL instead of String
Convert an NSURL to NSData
let data: NSData? = try? url.bookmarkDataWithOptions(.SuitableForBookmarkFile, includingResourceValuesForKeys: nil, relativeToURL: nil)
Read an NSURL from bookmark NSData
var isStale: ObjCBool = false
let url = try? NSURL(
byResolvingBookmarkData: bookData,
options: [],
relativeToURL: nil,
bookmarkDataIsStale: &isStale)
guard let fullURL = url else {
return nil
}
You can fill relativeToURL to your document directory url
Alternatively you can use FileKit : path.bookmarkData and Path(bookmarkData: ..)
try to persist your file just with the name.extension
to save document
let pathDocument = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0]
let fullPath = let fullPath = pathDocument+"/"+"fileName.ext"
//...add some code to save document at `fullPath`...
to get document
let pathDocument = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0]
let fullPath = let fullPath = pathDocument+"/"+"fileName.ext"
//... add code to get data at path : `fullPath`....

Permanent file directory in Xcode

In the documents directory for my app, I have a file Q1.dat which I use in my program. I access it through the path:
func createArrayPath () -> String? {
if let docsPath: String = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last {
return ((docsPath as NSString).stringByAppendingPathComponent("Q1") as NSString).stringByAppendingPathExtension("dat")
}
return nil
}
When I run the program on a different device however, a different documents directory is created, and the file is no longer present. Is there a place I can put the file so that I can always access it no matter what device I am running on?
The Documents directory is meant for data created by the user.
It sounds like you want to bundle a resource with your application. You can do this by simply dragging the file into Xcode, which will automatically set it up to be copied into your app bundle, and you can find it using URLForResource(_:withExtension:).
If the file is very large, you might want it to be downloaded separately from the main app. For this you can use the new On-Demand Resources feature.

Xcode and iOS app data file placements defaults

Is my understanding correct for iOS7-iOS9:
1)
"built-in" app cache path is NSHomeDirectory() + "/Library/Caches/"
2)
app launch images and icons are placed NSBundle.mainBundle().resourcePath! (where does this map down to?)
3) a "blue" folder I have added in "xcode - build phases - copy bundle resources called "ownassets"" is placed in...? NSHomeDirectory() + "/Library/"
I am just tying to make 100% sure if I understood correctly where files are placed, so I can read and load them during app execution (and write in my cache)
Note: I realize that release code should use system calls to get paths since Apple may changes paths in future iOS versions.
Note For hose looking on how to get normal IO file read access to folders and content you added in "Build phases > Copy Bundle Resources" this is how: NSBundle.mainBundle().resourcePath! + "/" + nameoffolder
You should not think much about the actual locations on disk, but use the higher-level system APIs to find files/paths:
Caches directory:
let cacheURL = try NSFileManager.defaultManager().URLForDirectory(.CachesDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
App resources in the bundle:
let image = UIImage(named: "imageName")
let path = NSBundle.mainBundle().pathForResource("image", ofType: "png")
App resources in subdirectories:
let path = NSBundle.mainBundle().pathForResource("info", ofType: "dat", inDirectory: "AdditionalResources")
For more info, see the File System Programming Guide.

Resources