Getting the resource path during testing - swift

I am trying to write a unit tests that uses a file in my project. In my application, I use FileManager.default.currentDirectoryPath to get the path to my file. However, the test path is different when I use the same in tesing. After reading up the documentation I understood that XCode uses a different path for unit testing.
I was wondering how I can get the correct Bundle path for File.txt in my tests
I have tried this but it returns null
let testBundle = Bundle(for: type(of: self))
let fileURL = testBundle.url(forResource: "File", withExtension: "txt")
The following is my directory structure. ShopTests is my unit test file and File.txt is the file for which I am trying to retrieve the path url for(both highlighted in picture)

Here is how I am doing it in a test that works:
let dataURL = Bundle(for: TripBuilderTest.self).url(forResource: fileName, withExtension: "json")
I think I remember having had the same problem you are reporting. Try using classname.self as per above.

Related

Swift - Read Google Sheets

I'm working on an app that uses Google Sheets as a database, but I can't figure out how to get Swift to read from google sheets. I've looked through the API website and a few questions on here but I need some help just getting started. So far I have;
private let scopes = [kGTLRAuthScopeSheetsSpreadsheets]
private let service = GTLRSheetsService()
var range = "Form Responses 1!A1:D3"
let spreadsheetId = "p;;;;;;p;;;;;;;;1LqXa6v75JE8RQQDOI4Z_g8mUT8x0DhsEDwRIaxDN-DU" // Portfolio
let query = GTLRSheetsQuery_SpreadsheetsValuesGet.query(withSpreadsheetId: spreadsheetId, range:range)
service.executeQuery(query, delegate: self, didFinish: #selector(displayResultWithTicket(ticket:finishedWithObject:error:)))
Which I got from another question on here...
But 'displayResultWithTicket' is an unresolved identifier. Currently it gets to the last line, and debugging I'm not even sure what to do with the 'query' value. I'm really not even sure if it's reading the correct spreadsheet. How can I tell?
Long story short, I'm lost.
I recently made an app that uses Google Sheets. But I used the CSV file for the database. This might help. If you want, I can share the details.
First you need to export the Google Sheets file in CSV format. I used Realm to read CSV. Using Realm Studio, you need to create the columns as in the CSV file. Then you can import the CSV file into Realm Studio. Your database is ready.
In didFinishLaunchingWithOptions to find the file created after installing Realm on your project
print(Realm.Configuration.defaultConfiguration.fileURL!.path)
Now we will use the database with Swift.
For this, we must first add the Realm file that we prepared to the XCode project directory. Then we use it in ViewController this way to get data.
var realm : Realm!
For get the data in default.realm file
let realmPath = Bundle.main.url(forResource: "default", withExtension: "realm")!
let realmConfiguration = Realm.Configuration(fileURL: realmPath, readOnly: true)
do{
realm = try Realm(configuration: realmConfiguration)
}
catch {
print("error \(error.localizedDescription)")
}
You can export the result to an array. I hope it helps.

Find latest modified file in Folder

I'm trying to find the latest text file in a folder so I can open it. So far I have:
let logFolder = URL(fileURLWithPath: "/Users/me/Library/Logs" )
let fm = FileManager.default
var files = try fm.contentsOfDirectory(at: logFolder, includingPropertiesForKeys: [.creationDateKey], options: [])
let txtFilePaths = files.filter{$0.pathExtension == "txt"}
But then I get stuck. I know I can get the date for a file with txtFilePath[x].creationDate
Seems like there should be a simple way of doing this but I'm a newbie and struggling to find any web resources for Swift 5.
Cheers
Such information about files is stored in something that is usually referred to as metadata.
I believe you are looking for something like NSMetadataItem.
By following the steps presented in this response, you should be able to have access to a field called kMDItemContentModificationDate. This should help you achieve your goal.

How to get original path when alias fails to resolve

How can the original target path be programatically retrieved when the alias fails to resolve?
do {
let resolutionOptions: URL.BookmarkResolutionOptions = [
.withoutUI, .withoutMounting
]
let _ = try URL(resolvingAliasFileAt: fileURL, options: resolutionOptions)
}
catch _ {
// since non-resolvable, then retrieve & print original target string
}
The existing StackOverflow question "Getting alias path of file in swift" does not cover original target path retrieval for the situation of a non-resolvable alias.
The information would seem to be available somehow because the Finder GUI Get Info will still show the Original: /Some/Path even if the original is not found or available.
Also, mdls metadata listing did not provide the original target path.
I think you can load the bookmark data using URL.bookmarkData(withContentsOf:), then use resourceValues(forKeys:fromBookmarkData:) with [.pathKey] as the keys. Then, query the path of the returned URLResourcesKey object.

Connect a SQLite Database in Swift

I have a problem when I try to create the path to my database in my iOS Application. I am a beginner in SQLite so I prefer ask here to have an answer.
I use this gitHub source of SQLite 3 for make and use a database in Swift, a GitHub source: https://github.com/stephencelis/SQLite.swift and I have an error which appears: "Missing argument label 'coder:' in call".
Then I fix this error by putting coder: before my path and another error appears: "Cannot convert value of type 'String' to expected argument 'NSCoder'.
static let path = NSSearchPathForDirectoriesInDomains( .documentDirectory, .userDomainMask, true).first!
static let db = try Connection(coder: "\(path)/data.sqlite3")
The problem was solve with delete and put sqlite again.
Thanks for the help.

Is it possible to read entitlements files in swift

I am implementing universal deep linking in my app. When I registered my different domains, it creates an AppName.entitlements file
I would like to read the values of this file like a plist.
I tried
if let path = NSBundle.mainBundle().pathForResource("AppName", ofType:
"entitlements") { }
but it returns nil
Is it possible to read such files?
That file isn't copied in to your app (see Xcode's target checkbox). It is only used for building
the entitlements are a config file for Xcode
so: no
The solution I found:
add the appGroup into Info.Plist file
<key>appGroup</key>
<string>group.com.acronis.mobile.ios.development</string>
To read the string use the code below:
extension String {
// MARK: - Static
static var appGroup: String = {
guard let bundleAppGroup = Bundle.main.infoDictionary?["appGroup"] as? String else {
fatalError("The application must contain appGroup in Info.plist file")
}
return bundleAppGroup
}()
}
Change the entitlements and Info.plist at before build time using your custom script if needed.
I dove into this subject a bit and it is actually quite simple.
You use a run script to grab the entitlements and merge it into Info.plist:
ENTITLEMENTS= # Path to Project.entitlements #
INFOPLIST= # Path to Info.plist #
echo "Writing entitlements to Info.plist";
KEY="entitlements-from-script";
/usr/libexec/PlistBuddy -c "delete $KEY" "$INFOPLIST";
/usr/libexec/PlistBuddy -c "add $KEY dict" "$INFOPLIST";
/usr/libexec/PlistBuddy -c "merge $ENTITLEMENTS $KEY" "$INFOPLIST";
Now you can use it in code:
let entitlements = Bundle.main.infoDictionary?["entitlements-from-script"]
While looking into this I found the following blog post
https://medium.com/swlh/reading-application-entitlements-with-swift-65cff184e840
where #mateuszmatrejek explains how to parse the binary file at run time to extract the entitlements.
This approach is very low level and complex. The key advantage I see with this approach is if you are working on a framework or library this would work to read the entitlements of the app which is using importing your lib or framework.