swift 3 convert string to objectID - macos

i work with swift 3 and nsoutlineview.
i would like to save the objectID of a core data record into a textfield.
so i have to convert it into a string:
txtFied.stringValue = "\(CoreData[outlineView.selectedRow].objectID)"
how can i convert it back to an NSManagedObjectID?

I've done this via the persistent store coordinator's managedObjectID(forURIRepresentation:) method, as outlined below:
// Convert NSManagedObjectID to a string, via the uriRepresentation method.
let objectIDString = <your managed object ID>.uriRepresentation().absoluteString
...
// Use the persistent store coordinator to transform the string back to an NSManagedObjectID.
if let objectIDURL = URL(string: objectIDString) {
let coordinator: NSPersistentStoreCoordinator = <reference to your persistent store coordinator>
let managedObjectID = coordinator.managedObjectID(forURIRepresentation: objectIDURL)
}

Related

Opening and using a database from another view controller

I have created a database in one view controller and I would like to open it and access it in another view controller. I was wondering how to open up a existing database from one view controller in another view controller. I intend to open up the database and be able to update a row, so I would also need access to the "parts" (ex. id, name, email). Could you help me? Anything would be helpful. Thanks!
You can access your DB from any VC. Code (which you will probably use anywhere you want to access your DB from) would be like
let path = NSSearchPathForDirectoriesInDomains(
.documentDirectory, .userDomainMask, true
).first!
do {
let db = try Connection("\(path)/<your.db.filename>")
let recordsTable = Table("records")
//or whatever you'd like to do, extract, modify, insert or delete
}
catch let error {
print("Data operation failed for records table: \(error)")
}
Instead of copying same code all over your project, you can separately create your own class for any of your DB operations and access it from anywhere:
class DatabaseOps {
//..
func getHighscoreTable() -> Array<HighScoreDataArray> {
let path = NSSearchPathForDirectoriesInDomains(
.documentDirectory, .userDomainMask, true
).first!
var highscores = [HighScoreDataArray]()
do {
let db = try Connection("\(path)/tasksolver.db")
let score = Expression<Int>("Score")
let username = Expression<String>("Username")
let recordsTable = Table("records").order(score.desc).limit(10)
for row in try db.prepare(recordsTable) {
let highscore = HighScoreDataArray(score: Int(row[score]), username: String(row[username]))
highscores += [highscore]
}
} catch let error {
print("Data operation failed for records table: \(error)")
}
return highscores
}
//..
}
class RecordsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var myDb : DatabaseOps = DatabaseOps()
//...
super.viewDidLoad()
//get the data from database by using myDB method
myHighScoreTable = myDb.getHighscoreTable()
Also, before you try it in different VCs - don't forget to make sure you have your DB file in place. If it is not, let db = try Connection will create an empty database for you, which will not contain any of your data or tables you want to access.

NSDictionary to Json in Xamarin.iOS

I am trying to convert the NSDictionary into Json using NSJsonSerialization.Serialize. But i am not getting expected output
Code in Xamarin.iOS
var dictionary = new NSDictionary(
new NSString("userName"), new NSString("450012"),
new NSString("password"), new NSString("Abc134"),
new NSString("companyId"), new NSString("CM1")
);
request.Body = NSJsonSerialization.Serialize(dictionary, 0, out error);
the problem is that value of dictionary variable is showing
{{password":Abc134,companyId:CM1,userName:450012}}
instead of
{password:Abc134,companyId:CM1,userName:450012}
it is adding one curly braces at the front and back
is there any way to generate proper json string for user input values
There's nothing wrong with your json. If you print it in the console you will see that the value being printed is the value you expect.
{"password":"Abc134","companyId":"CM1","userName":"450012"}
Give it a try with:
Console.WriteLine($"{json}");
If you really, really want to get rid of of that "extra" curly braces just convert the result into string.
var jsonString = json.ToString();
The above should do the work.
I would just suggest you changing your method to this:
var json2 = NSJsonSerialization.Serialize(dictionary, NSJsonWritingOptions.PrettyPrinted, out error);
Using the PrettyPrinted option.
Hope this helps.-
Yes, you can try to create a custom object to serialize. Create a simple plain object to hold the data you want.
User user = new User() {
UserName = "JohnDoe",
Password = "xxx",
CompanyId = 01
};
request.Body = NSJsonSerialization.Serialize(user, 0, out error);
Then serialize it and you will see the proper json well formed.

How to bind FloatRatingView rating to variable using RxSwift

I am attempting to integrate this library with my RxSwift project, https://github.com/glenyi/FloatRatingView
I am unable to get the updated rating.
Here is how I have created the FloatRatingView in the Controller,
let starRater : FloatRatingView = {
let floatRatingView = FloatRatingView()
floatRatingView.emptyImage = UIImage(named: "EmptyStar")
return floatRatingView
}()
The Model contains the following,
let my_rating = Variable<Float?>(nil)
What I want to be able to do is to update the value in the my_rating variable when a user changes the rating by tapping on a star. Here is what I've written for this,
_ = starRater.rx.rating
.asObservable()
.bindTo(viewModel.my_rating.rx_value)
But here is the error I'm receiving.
Value of type 'Reactive FloatRatingView' has no member 'rating'
Here is how I will retrieve the value from my_rating variable,
let stars = self.my_rating.value
Kindly help me out. Thanks.
You need to add a bindable sink for the property, it would be something like this:
extension Reactive where Base: FloatRatingView {
/// Bindable sink for `rating` property
public var progress: UIBindingObserver<Base, Float> {
return UIBindingObserver(UIElement: self.base) { floatRatingView, rating in
floatRatingView.rating = rating
}
}
}

How to implement two way binding with Swift?

How to implement a two way data binding using Swift 2.0?
Let's assume I have the following model class (using couchbase lite):
#objc(Person)
class Person: NSObject{
#NSManaged var firstName: NSString?
#NSManaged var lastName: NSString?
}
And I like to bind the properties to a given formItemDescriptor like this:
class FormItemDescriptor {
var tag: String?
var value: Any?
}
How would I bind the FormItemDescriptor.value property to the Person.firstName property using 2-way-binding?
So changes in the model appear in the form and vice versa?
Swift does not support bindings out of the box, but you can achieve them with frameworks like ReactiveKit.
For example, when you declare an observable property you can bind it to another observable property.
let numberA: Property<Int>
let numberB: Property<Int>
numberA.bindTo(numberB)
To do bi-directional, just bind in other direction too:
numberB.bindTo(numberA)
Now, whenever you change any of them, the other will change.
Your example is bit harder though because you need to do bindings from #NSManaged properties that cannot be made Observable. It's not impossible, but to work the properties of Person should support key-value observing (KVO).
For example, given a Person object and a label, you could take an Property from KVO-enabled property with the method rValueForKeyPath and then bind that observable to the label, like this:
let person: Person
let nameLabel: UILabel
person.rValueForKeyPath("firstName").bindTo(nameLabel)
If you have an intermediately object like your FormItemDescriptor, then you'll have to make its properties observable.
class FormItemDescriptor {
var tag: Property<String?>
var value: Property<Any?>
}
Now you could establish binding
let person: Person
let descriptor: FormItemDescriptor
person.rValueForKeyPath("firstName").bindTo(descriptor.value)
Because firstName is not observable, you cannot do binding in another direction so you'll have to update it manually whenever value changes.
descriptor.value.observeNext { value in
person.firstName = value as? NSString
}
We also had to do cast to NSString because value is of type Any?. You should rethink that though and see if you can make it a stronger type.
Note that UIKit bindings are coming from ReactiveUIKit framework. Check our documentation of ReactiveKit for more info.

IOS Swift defining own app-settings in own class

im new in Swift and X-Code. Im searching for a way import a own defined class (best case in an own document). I want store all needed settings (text-snippets and app-settings) in this file. For example:
class snippetsAndSettings {
// e.g translations
let t_welcome: String = "Welcome to my App"
let t_share: String = "Social Share Buttons"
let t_rate: String = "Rate"
// e.g settings
let s_weburl: String = "http://www.mypage.com/webservice.php"
let s_slider: Bool = false
let s_bgColor: String = "#ff9900"
let s_tColor: String = "#222222"
let t_shadow: String? // Bool or colorString!
}
I want to use this class on every app-page. But i can not import the for for example in ViewController.swift
My questions:
In which format do i have to save the file (snippetsAndSettings)? Cocoa Class
How can i import the file in my ViewController.Swift
Is this a common way to store own app-settings in Swift?
The method to store settings is via NSUserDefaults. You can setup your default values in your app delegate's application:didFinishLaunchingWithOptions: method. For example:
NSUserDefaults.standardUserDefaults().registerDefaults([
"volume": 100,
"showShadows": true
])
To get these back, you would do:
NSUserDefaults.standardUserDefaults().integerForKey("volume")
and
NSUserDefaults.standardUserDefaults().boolForKey("showShadows")
In Swift 5, it now looks like this:
UserDefaults.standard.register(defaults: [
"volume": 100,
"showShadows": true
])
And to get it back
let volume = UserDefaults.standard.integer(forKey: "volume")
let showShadows = UserDefaults.standard.bool(forKey: "showShadows")
For translations, you should look in to Internationalization and Localization

Resources