I have seen this code in other post, for save pictures:
// Create path.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"Image.png"];
// Save image.
[UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES];
An d I'm trying convert to swift for save a picture take with avfoundatioin but I dont know type NSDocumentDirectory and NSUserDomainMask here
How can convert this??
Thanks!!
As follows:
let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
if let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true) {
if paths.count > 0 {
if let dirPath = paths[0] as? String {
let readPath = dirPath.stringByAppendingPathComponent("Image.png")
let image = UIImage(named: readPath)
let writePath = dirPath.stringByAppendingPathComponent("Image2.png")
UIImagePNGRepresentation(image).writeToFile(writePath, atomically: true)
}
}
}
"paths" is an AnyObject[], so you have to check that its elements can be converted to String.
Naturally, you wouldn't actually use "NSDocumentDirectory" as the name, I just did it for clarity.
Update for Xcode 7.2
NSSearchPathForDirectoriesInDomains now returns [String] rather than [AnyObject]? so use
let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
if let dirPath = paths.first {
// ...
}
The fact that .stringByAppendingPathComponent is also deprecated is dealt with in this answer...
Here is what I use:
let fileManager = NSFileManager.defaultManager()
let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
let documentsURL = fileManager.URLsForDirectory(nsDocumentDirectory, inDomains: nsUserDomainMask).last
This is just a rework of #पवन answer working for Swift 3
import Foundation
import UIKit
import ImageIO
import MobileCoreServices
extension UIImage
{
func write(at path:String) -> Bool
{
let result = CGImageWriteToFile(image: self.cgImage!, filePath: path)
return result
}
private func CGImageWriteToFile(image:CGImage, filePath:String) -> Bool
{
let imageURL:CFURL = NSURL(fileURLWithPath: filePath)
var destination:CGImageDestination? = nil
let ext = (filePath as NSString).pathExtension.lowercased()
if ext == "jpg" || ext == "jpeg"
{
destination = CGImageDestinationCreateWithURL(imageURL, kUTTypeJPEG, 1, nil)
}
else if ext == "png" || ext == "pngf"
{
destination = CGImageDestinationCreateWithURL(imageURL, kUTTypePNG, 1, nil)
}
else if ext == "tiff" || ext == "tif"
{
destination = CGImageDestinationCreateWithURL(imageURL, kUTTypeTIFF, 1, nil)
}
else if ext == "bmpf" || ext == "bmp"
{
destination = CGImageDestinationCreateWithURL(imageURL, kUTTypeBMP, 1, nil)
}
guard destination != nil else {
fatalError("Did not find any matching path extension to store the image")
}
CGImageDestinationAddImage(destination!, image, nil)
if CGImageDestinationFinalize(destination!)
{
return true
}
return false
}
}
And the usage
let pickedImage = UIImage()
let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as NSString).appendingPathComponent("image.tif")
if pickedImage.write(at: path) == false
{
print("failed to write file to disk!")
}
Use this category to save any image on document directory
import Foundation
import UIKit
import ImageIO
import MobileCoreServices
extension UIImage {
func writeAtPath(path:String) -> Bool {
let result = CGImageWriteToFile(self.CGImage!, filePath: path)
return result
}
private func CGImageWriteToFile(image:CGImageRef, filePath:String) -> Bool {
let imageURL:CFURLRef = NSURL(fileURLWithPath: filePath)
var destination:CGImageDestinationRef? = nil
let ext = (filePath as NSString).pathExtension.uppercaseString
if ext == "JPG" || ext == "JPEG" {
destination = CGImageDestinationCreateWithURL(imageURL, kUTTypeJPEG, 1, nil)
} else if ext == "PNG" || ext == "PNGF" {
destination = CGImageDestinationCreateWithURL(imageURL, kUTTypePNG, 1, nil)
} else if ext == "TIFF" || ext == "TIF" {
destination = CGImageDestinationCreateWithURL(imageURL, kUTTypeTIFF, 1, nil)
} else if ext == "GIFF" || ext == "GIF" {
destination = CGImageDestinationCreateWithURL(imageURL, kUTTypeGIF, 1, nil)
} else if ext == "PICT" || ext == "PIC" || ext == "PCT" || ext == "X-PICT" || ext == "X-MACPICT" {
destination = CGImageDestinationCreateWithURL(imageURL, kUTTypePICT, 1, nil)
} else if ext == "JP2" {
destination = CGImageDestinationCreateWithURL(imageURL, kUTTypeJPEG2000, 1, nil)
} else if ext == "QTIF" || ext == "QIF" {
destination = CGImageDestinationCreateWithURL(imageURL, kUTTypeQuickTimeImage, 1, nil)
} else if ext == "ICNS" {
destination = CGImageDestinationCreateWithURL(imageURL, kUTTypeAppleICNS, 1, nil)
} else if ext == "BMPF" || ext == "BMP" {
destination = CGImageDestinationCreateWithURL(imageURL, kUTTypeBMP, 1, nil)
} else if ext == "ICO" {
destination = CGImageDestinationCreateWithURL(imageURL, kUTTypeICO, 1, nil)
} else {
fatalError("Did not find any matching path extension to store the image")
}
if (destination == nil) {
fatalError("Did not find any matching path extension to store the image")
return false
} else {
CGImageDestinationAddImage(destination!, image, nil)
if CGImageDestinationFinalize(destination!) {
return false
}
return true
}
}
}
// This is how to use this category in your application.
func testImageWrite() -> Bool {
let img = UIImage(named: "test")
var path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0]
path = (path as NSString).stringByAppendingPathComponent("Test.png")
let result = img?.writeAtPath(path)
return result!
}
For xCode 8.1, swift 3.0 you can do:
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
I think this is a lot cleaner and shorter.
Related
I have already copy the file absolute path and paste in simulator browser, the image can be opened. But the fileExists is fail, i dont know why..... Can anyone help
let defaultImage = "302C3FA1-E4E1-4CD8-B6DF-2FF4E4E24C11.jpeg"
loadImage(at: defaultImage)
func fileExists(at path: String) -> Bool {
return FileManager.default.fileExists(atPath: path)
}
func loadImage(at path: String) -> UIImage? {
let tempPath = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
let imagePath = "\(tempPath)\(path.trimmingCharacters(in: .whitespacesAndNewlines))"
guard fileExists(at: imagePath) else { return nil }
guard let image = UIImage(contentsOfFile: imagePath) else { return nil }
return image
}
You need split filename and extension filename.
If you use main bundle. you can follow this code
let stringPath = Bundle.main.path(forResource: "your_filename", ofType: "txt")
let urlPath = Bundle.main.url(forResource: "your_filename", withExtension: "txt")
or you can use my code.
func readConfigFromBundle(fileExtension: String) -> TCBConfigure? {
let bundle = Bundle.main
if let resPath = bundle.resourcePath {
do {
let dirContents = try FileManager.default.contentsOfDirectory(atPath: resPath)
let filteredFiles = dirContents.filter { $0.contains(fileExtension) }
for fileName in filteredFiles {
let sourceURL = bundle.bundleURL.appendingPathComponent(fileName)
let data: NSData? = NSData.init(contentsOf: sourceURL)
if let fileData = data {
// implement your logic
}
}
} catch {
// implement when error
}
}
return nil
}
I am working on UICollectionView fetching gallery images and shown in UICollectionViewCell but i need to shown all images within one single folder.
Is there any solution for this?
You can try this way.Below code is fetch the "Repost" folder from gallery and fetch all the photos of it.
func getImages() {
image = []
let albumName = "Repost" //album name
let fetchOptions = PHFetchOptions()
var assetCollection = PHAssetCollection()
fetchOptions.predicate = NSPredicate(format: "title = %#", albumName)
let collection:PHFetchResult = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)
if let _:AnyObject = collection.firstObject{
//found the album
assetCollection = collection.firstObject!
albumFound = true
}
else { albumFound = false
print("album not found")
}
let assets = PHAsset.fetchAssets(in: assetCollection, options: nil) as! PHFetchResult<AnyObject>
assets.enumerateObjects({ (object, count, stop) in
// self.cameraAssets.add(object)
if object.mediaType == .image
{
self.image.append(object as! PHAsset) // for image
}
})
self.image.reverse()
self.imgcollection.reloadData()
}
Don't forgot to import photos framework.
Thanks.
In case you are still struggling to figure out here is the code snippet, good luck
func saveImageToDocumentDirectory(image: UIImage ) {
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let fileName = "image001.png" // name of the image to be saved
let fileURL = documentsDirectory.appendingPathComponent(fileName)
if let data = UIImageJPEGRepresentation(image, 1.0),!FileManager.default.fileExists(atPath: fileURL.path) {
do {
try data.write(to: fileURL)
print("file saved")
} catch {
print("error saving file:", error)
}
}
}
func loadImageFromDocumentDirectory(nameOfImage : String) -> UIImage {
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
if let dirPath = paths.first {
let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(nameOfImage)
let image = UIImage(contentsOfFile: imageURL.path)
return image!
}
return UIImage.init(named: "default.png")!
}
I have to share image on instagram with caption but in Instagram nothing is coming. I used below code for sharing on instagram. Is there any changes in code of sharing. I also check the official page of Instagram but no code is given. https://www.instagram.com/developer/mobile-sharing/iphone-hooks/
Following code is working till ios10 but in ios11 it is not working any more.
File write successfully in document directory but problem was in UIDocumentInteractionController. It is not able to read file from document directory.
//MARK:
//MARK: share with instagram
func shareImageToInstagram(withImagePath imgPath:String,withStrTitle strTitle:String,withView view:UIView,withSender sender:UIButton! = nil) {
let instagramURL = URL(string: "instagram://app")
if UIApplication.shared.canOpenURL(instagramURL!) {
interactionController = UIDocumentInteractionController(url: URL.init(fileURLWithPath: imgPath))
interactionController?.uti = "com.instagram.photos"
interactionController?.annotation = NSDictionary.init(dictionaryLiteral: ("InstagramCaption",strTitle))
interactionController?.presentOpenInMenu(from: CGRect.zero, in: view, animated: true)
sender.isUserInteractionEnabled = true
}
}
//MARK:
//MARK: share with instagram
func downloadUserImageFromURL(withImageUrl imgURl : URL,withView view:UIView,withstrTitle strTitle:String,withSender sender:UIButton! = nil){
DispatchQueue.global(qos: .userInitiated).async {
do {
DispatchQueue.main.async {
SINGLETON.startLoadingActivity(view)
}
let data = try Data.init(contentsOf: imgURl) //make sure your image in this url does exist, otherwise unwrap in a if let check
DispatchQueue.main.async {
SINGLETON.stopLoadingActivity(view)
//create instance of NSFileManager
let paths: [Any] = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
//create an array and store result of our search for the documents directory in it
let documentsDirectory: String = paths[0] as? String ?? ""
//create NSString object, that holds our exact path to the documents directory
let fullPath: String = URL(fileURLWithPath: documentsDirectory).appendingPathComponent("insta.igo").absoluteString
//add our image to the path
if FileManager.default.fileExists(atPath: fullPath)
{
do {
try FileManager.default.removeItem(at: URL.init(string: fullPath)!)
} catch let error as NSError {
sender.isUserInteractionEnabled = true
print(error.localizedDescription)
}
}
do {
try data.write(to: URL.init(string: fullPath)!)
self.shareImageToInstagram(withImagePath: fullPath, withStrTitle: strTitle, withView: view,withSender: sender)
} catch let error as NSError {
sender.isUserInteractionEnabled = true
print(error.localizedDescription)
}
}
}
catch{
DispatchQueue.main.async {
SINGLETON.stopLoadingActivity(view)
}
}
}
}
You use wrong UTI: "com.instagram.photos" should be "com.instagram.photo".
Also don't forget to add URL scheme instagram into plist at Key LSApplicationQueriesSchemes.
Here you can find example of sharing into Instagram (method - (void)send).
Main code from there:
Objective-C:
// make a path into documents
NSString* homePath = [self _getpathToDocuments];
NSString* basePath = #"integration/instagram";
NSString* tmpFileName;
if ([self _isInstagramOnly]) {
tmpFileName = #"jumpto.igo";
} else {
tmpFileName = #"jumpto.ig";
}
NSString* dirPath = [NSString stringWithFormat:#"%#/%#", homePath, basePath];
NSString* docPath = [NSString stringWithFormat:#"%#/%#", dirPath, tmpFileName];
[[NSFileManager defaultManager] removeItemAtPath:docPath error:nil];
if ([[NSFileManager defaultManager] createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:nil]) {
UIImage* tmpImg = [self _imageForSharing];
if([self _needResizeImage]){
tmpImg = [self _resizeImage:tmpImg];
}
NSData* imgData = [self generateImageData:tmpImg];
[[NSFileManager defaultManager] createFileAtPath:docPath contents:imgData attributes:nil];
NSURL* url = [NSURL fileURLWithPath:docPath isDirectory:NO ];
NSString *UTI = nil;
if ([self _isInstagramOnly]) {
UTI = #"com.instagram.exclusivegram";
} else {
UTI = #"com.instagram.photo";
}
NSString *captionString = #"Caption message";
UIDocumentInteractionController* dic = [UIDocumentInteractionController interactionControllerWithURL:documentFileURL];
dic.UTI = UTI;
dic.annotation = #{#"InstagramCaption" : captionString};
dic.delegate = self;
[self presentOpenInMenuFromRect:[self _getButtonRect] inView:self.view animated:YES];
}
Swift:
// Converted with Swiftify v1.0.6491 - https://objectivec2swift.com/
// make a path into documents
var homePath: String = _getpathToDocuments()
var basePath = "integration/instagram"
var tmpFileName = ""
if _isInstagramOnly() {
tmpFileName = "jumpto.igo"
}
else {
tmpFileName = "jumpto.ig"
}
var dirPath = "\(homePath)/\(basePath)"
var docPath = "\(dirPath)/\(tmpFileName)"
try? FileManager.default.removeItem(atPath: docPath)
if try? FileManager.default.createDirectory(atPath: dirPath, withIntermediateDirectories: true, attributes: nil) != nil {
var tmpImg: UIImage? = _imageForSharing()
if _needResizeImage() {
tmpImg = _resize(tmpImg)
}
var imgData = generateImageData(tmpImg)
FileManager.default.createFile(atPath: docPath, contents: imgData, attributes: nil)
var url = URL.fileURL(withPath: docPath, isDirectory: false)
var UTI: String? = nil
if _isInstagramOnly() {
UTI = "com.instagram.exclusivegram"
}
else {
UTI = "com.instagram.photo"
}
var captionString = "Caption message"
var dic = UIDocumentInteractionController(url: documentFileURL)
dic.uti = UTI
dic.annotation = ["InstagramCaption": captionString]
dic.delegate = self
presentOpenInMenu(from: _getButtonRect(), in: view, animated: true)
}
I am using the documents directory of my application to cache images locally, but when I go to access them, they are not updated until I close the app and reopen.
Here is my save:
var readPath = ""
let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
if let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true) {
if paths.count > 0 {
if let dirPath = paths[0] as? String {
readPath = dirPath.stringByAppendingPathComponent("\(user).png")
UIImagePNGRepresentation(imageView.image).writeToFile(readPath, atomically: true)
}
}
}
Here is my retrieval:
var readPath = ""
let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
if let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true) {
if paths.count > 0 {
if let dirPath = paths[0] as? String {
readPath = dirPath.stringByAppendingPathComponent("\(user).png")
//UIImagePNGRepresentation(imageView.image).writeToFile(readPath, atomically: true)
}
}
}
let cachedImage = UIImage(named: readPath)
if (cachedImage != nil)
{
println("cached")
self.userPictures.append(cachedImage!)
}
For some reason though, it is not until I have reset the application that these resources become available.
Can anyone shed some light on why this could be?
The image that gets returned to cachedImage is an image that I had previously saved into that specific path btw
This may helps you....
let fileManager = NSFileManager.defaultManager()
var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String
var getImagePath = paths.stringByAppendingPathComponent("\(fileName).png")
if (fileManager.fileExistsAtPath(getImagePath))
{
println("FILE AVAILABLE");
//Pick Image and Use accordingly
var imageis: UIImage = UIImage(contentsOfFile: getImagePath)!
self.image = imageis // UIImageView Class
let datas: NSData = UIImagePNGRepresentation(imageis)
}
else
{
println("FILE NOT AVAILABLE");
let getImage = UIImage(data: self.data)
self.image = getImage
var filePathToWrite = "\(paths)/\(fileName).png"
var imageData: NSData = UIImagePNGRepresentation(self.image)
fileManager.createFileAtPath(filePathToWrite, contents: imageData, attributes: nil)
}
Check the Project in Github
I am trying to save data to a plist file in swift, but the data isn't showing up as it was saved when the plist is read. This is the code I was using.
var documentsDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
var path : NSString = documentsDirectory.stringByAppendingPathComponent("data.plist")
var data : NSMutableDictionary = NSMutableDictionary(contentsOfFile: path)
data.setObject(self.object, forKey: "key")
data.writeToFile(path, atomically: true)
Edit: I've heard that the best way to do this is write to the documents directory, so my question would be how should I write to a file in that directory?
Apparently the file is not in a writable location, so I created it in the documents directory.
var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
var path = paths.stringByAppendingPathComponent("data.plist")
var fileManager = NSFileManager.defaultManager()
if (!(fileManager.fileExistsAtPath(path)))
{
var bundle : NSString = NSBundle.mainBundle().pathForResource("data", ofType: "plist")
fileManager.copyItemAtPath(bundle, toPath: path, error:nil)
}
data.setObject(object, forKey: "object")
data.writeToFile(path, atomically: true)
Then, it has to be read from the documents directory.
var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
var path = paths.stringByAppendingPathComponent("data.plist")
let save = NSDictionary(contentsOfFile: path)
Swift 3:
func loadData() {
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as NSArray
let documentDirectory = paths[0] as! String
let path = documentDirectory.appending("myData.plist")
let fileManager = FileManager.default
if(!fileManager.fileExists(atPath: path)){
if let bundlePath = Bundle.main.path(forResource: "myData", ofType: "plist"){
let result = NSMutableDictionary(contentsOfFile: bundlePath)
print("Bundle file myData.plist is -> \(result?.description)")
do{
try fileManager.copyItem(atPath: bundlePath, toPath: path)
}catch{
print("copy failure.")
}
}else{
print("file myData.plist not found.")
}
}else{
print("file myData.plist already exits at path.")
}
let resultDictionary = NSMutableDictionary(contentsOfFile: path)
print("load myData.plist is ->\(resultDictionary?.description)")
let myDict = NSDictionary(contentsOfFile: path)
if let dict = myDict{
myItemValue = dict.object(forKey: myItemKey) as! String?
txtValue.text = myItemValue
}else{
print("load failure.")
}
}
Read and Write plist file in swift
Check in Xcode 10 swift 4.1
//TODO: for wtite in .plist file
let docsBaseURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let customPlistURL = docsBaseURL.appendingPathComponent("custom.plist")
print(customPlistURL.absoluteString)
let dic:[String:Any] = ["key":"val"]
// Swift Dictionary To Data.
do {
let data = try PropertyListSerialization.data(fromPropertyList: dic, format: PropertyListSerialization.PropertyListFormat.binary, options: 0)
do {
try data.write(to: customPlistURL, options: .atomic)
print("Successfully write")
}catch (let err){
print(err.localizedDescription)
}
}catch (let err){
print(err.localizedDescription)
}
Use writeToFile:options:error: and see what the error says:
var error: NSError?
var bytes = NSKeyedArchiver.archivedDataWithRootObject(data)
if !bytes.writeToFile(path, options: nil, error: &error) {
if let actualError = error {
println(actualError)
}
}
struct Plist {
enum PlistError: ErrorType {
case FileNotWritten
case FileDoesNotExist
}
let name:String
var sourcePath:String? {
guard let path = NSBundle.mainBundle().pathForResource(name, ofType: "plist") else { return .None }
return path
}
var destPath:String? {
guard sourcePath != .None else { return .None }
let dir = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
return (dir as NSString).stringByAppendingPathComponent("\(name).plist")
}
init?(name:String) {
self.name = name
let fileManager = NSFileManager.defaultManager()
guard let source = sourcePath else { return nil }
guard let destination = destPath else { return nil }
guard fileManager.fileExistsAtPath(source) else { return nil }
if !fileManager.fileExistsAtPath(destination) {
do {
try fileManager.copyItemAtPath(source, toPath: destination)
} catch let error as NSError {
print("Unable to copy file. ERROR: \(error.localizedDescription)")
return nil
}
}
}
func getValuesInPlistFile() -> NSDictionary?{
let fileManager = NSFileManager.defaultManager()
if fileManager.fileExistsAtPath(destPath!) {
guard let dict = NSDictionary(contentsOfFile: destPath!) else { return .None }
return dict
} else {
return .None
}
}
func getMutablePlistFile() -> NSMutableDictionary?{
let fileManager = NSFileManager.defaultManager()
if fileManager.fileExistsAtPath(destPath!) {
guard let dict = NSMutableDictionary(contentsOfFile: destPath!) else { return .None }
return dict
} else {
return .None
}
}
func addValuesToPlistFile(dictionary:NSDictionary) throws {
let fileManager = NSFileManager.defaultManager()
if fileManager.fileExistsAtPath(destPath!) {
if !dictionary.writeToFile(destPath!, atomically: false) {
print("File not written successfully")
throw PlistError.FileNotWritten
}
} else {
throw PlistError.FileDoesNotExist
}
}
}
Now, implement below in your view controller.
if let plist = Plist(name: "plist file name") {
let dict = plist.getMutablePlistFile()!
dict["key"] = value
do {
try plist.addValuesToPlistFile(dict)
} catch {
print(error)
}
print(plist.getValuesInPlistFile())
} else {
print("Unable to get Plist")
}
From your Information Property List
Key
Privacy - Photo Library Additions Usage Description
Type
String
Value
"Your App Name" would like to access the photo gallery to manage your profile picture
updated swift code of Rebeloper:
let BedroomFloorKey = "BedroomFloor"
let BedroomWallKey = "BedroomWall"
var bedroomFloorID: AnyObject = 101
var bedroomWallID: AnyObject = 101
func saveGameData()
{
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
let documentsDirectory = paths.objectAtIndex(0) as! NSString
let path = documentsDirectory.stringByAppendingPathComponent("GameData.plist")
let dict: NSMutableDictionary = ["XInitializerItem": "DoNotEverChangeMe"]
//saving values
dict.setObject(bedroomFloorID, forKey: BedroomFloorKey)
dict.setObject(bedroomWallID, forKey: BedroomWallKey)
//...
//writing to GameData.plist
dict.writeToFile(path, atomically: false)
let resultDictionary = NSMutableDictionary(contentsOfFile: path)
print("Saved GameData.plist file is --> \(resultDictionary?.description)")
self.loadGameData()
}//eom
func loadGameData() {
// getting path to GameData.plist
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
let documentsDirectory = paths[0] as! NSString
let path = documentsDirectory.stringByAppendingPathComponent("GameData.plist")
// let path = documentsDirectory.stringByAppendingPathComponent("GameData.plist")
let fileManager = NSFileManager.defaultManager()
//check if file exists
if(!fileManager.fileExistsAtPath(path))
{
// If it doesn't, copy it from the default file in the Bundle
if let bundlePath = NSBundle.mainBundle().pathForResource("GameData", ofType: "plist")
{
let resultDictionary = NSMutableDictionary(contentsOfFile: bundlePath)
print("Bundle GameData.plist file is --> \(resultDictionary?.description)")
do
{
try fileManager.copyItemAtPath(bundlePath, toPath: path)
print("copy")
}
catch _
{
print("error failed loading data")
}
}
else
{
print("GameData.plist not found. Please, make sure it is part of the bundle.")
}
}
else
{
print("GameData.plist already exits at path.")
// use this to delete file from documents directory
//fileManager.removeItemAtPath(path, error: nil)
}
let resultDictionary = NSMutableDictionary(contentsOfFile: path)
print("Loaded GameData.plist file is --> \(resultDictionary?.description)")
let myDict = NSDictionary(contentsOfFile: path)
if let dict = myDict {
//loading values
bedroomFloorID = dict.objectForKey(BedroomFloorKey)!
bedroomWallID = dict.objectForKey(BedroomWallKey)!
//...
}
else
{
print("WARNING: Couldn't create dictionary from GameData.plist! Default values will be used!")
}
}//eom