I am working on a project containing a "Create New Account" view controller with its accompanying Swift class called "CreateNewAccount." The user can place 4 input values into this view controller, a first name, last name, user name, and password. Upon clicking the "Create Account" button in this VC, the 4 input values are passed on to a Swift class (within the model layer of MVC, I believe) called UserInfoRetrieveModel where they are supposedly stored.
I would then like to pass these values to another Swift class (that is a model as well) called UserInfoModel, which will then delegate out the first name value to the text value of label located in a VC called "ThanksForJoining" (and its accompanying class).
I have figured out how to pass values from VC to model (CreateNewAccount to UserInfoRetrieveModel) and from model to VC (UserInfoModel to ThanksForJoining), but somewhere in my transference from model to model (UserInfoRetrieveModel to UserInfoModel) the values initially inputted into "CreateNewAccount," which I would like to pass over to the second model class UserInfoModel become nil.
Below is the code for CreateNewAccount, UserInfoRetrieve, UserInfo, and ThanksForJoining:
CreateNewAccount ->
import UIKit
class CreateNewAccount: UIViewController{
#IBOutlet weak var FNInput: UITextField!
#IBOutlet weak var LNInput: UITextField!
#IBOutlet weak var usernameInput: UITextField!
#IBOutlet weak var passwordInput: UITextField!
var uInfoRetrieve = UInfoRetrieveModel()
#IBAction func thanksForJoining(_ sender: Any) {
uInfoRetrieve.firstName = FNInput.text!
uInfoRetrieve.lastName = LNInput.text!
uInfoRetrieve.userName = usernameInput.text!
uInfoRetrieve.password = passwordInput.text!
uInfoRetrieve.delegate = self
uInfoRetrieve.retrieving()
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension CreateNewAccount: UInfoRetrieveModelDelegate{
func credentialTransfer(data: String) {
print(data)
}
}
UserInfoRetrieve ->
import Foundation
protocol UInfoRetrieveModelDelegate: class {
func credentialTransfer(data:String)
}
class UInfoRetrieveModel: NSObject {
weak var delegate: UInfoRetrieveModelDelegate?
var firstName: String = ""
var lastName: String = ""
var userName: String = ""
var password: String = ""
func retrieving(){
delegate?.credentialTransfer(data: firstName)
delegate?.credentialTransfer(data: lastName)
delegate?.credentialTransfer(data: userName)
delegate?.credentialTransfer(data: password)
}
}
UserInfo ->
import Foundation
protocol UserInfoModelDelegate: class {
func didReceiveDataUpdate(data: String)
}
class UserInfoModel {
weak var delegate: UserInfoModelDelegate?
let uInfoRetrieve = UInfoRetrieveModel()
func requestData() -> Array<String> {
let firstName = uInfoRetrieve.firstName
let lastName = uInfoRetrieve.lastName
let userName = uInfoRetrieve.userName
let password = uInfoRetrieve.password
delegate?.didReceiveDataUpdate(data: firstName)
delegate?.didReceiveDataUpdate(data: lastName)
delegate?.didReceiveDataUpdate(data: userName)
delegate?.didReceiveDataUpdate(data: password)
let credentials = [firstName, lastName, userName, password] as [Any]
return credentials as! Array<String>
}
}
ThanksForJoining ->
import UIKit
class ThanksForJoining: UIViewController {
var userInfo = UserInfoModel()
#IBOutlet weak var firstName: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
userInfo.delegate = self
firstName.text = userInfo.requestData()[0]
print("yo")
print(userInfo.requestData()[0])
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ThanksForJoining: UserInfoModelDelegate {
func didReceiveDataUpdate(data: String) {
print(data)
}
}
UserInfoModel and CreateNewAccount do both create a new instance of UInfoRetrieveModel. You have to connect them properly for them to pass on information.
Connecting properly means (in the simplest form) one constructs the other and sets itself as the delegate of the other, so UInfoRetrieveModel can pass on data. The constructing of a child model is usually done via a computed property.
Example
struct Account {
let firstName: String, lastName: String
let userName: String, password: String
}
extension UInfoRetrieveModelDelegate: class {
createAccount(_ account: Account): Bool
}
extension UserInfoModel: UInfoRetrieveModelDelegate{
func createAccount(_ account: Account) -> Bool {
// Handling creation of account.
return success == true
}
var newUInfoRetrieveModel: UInfoRetrieveModel {
let helperModel = UInfoRetrieveModel(parent: self)
helperModel.delegate = self
return helperModel
}
}
Explanation
Yes. You usually have a Model, your data, then have something that controls access to it to make changes on your model, manages how the model is stored, maybe syncing with a cloud-service, thats the ModelController which you pass around between ViewControllers, more/other controllers you usually use incase that makes things simpler. In your case you would probably pass createAccount(the call) on to a controller/viewController which is in charge of telling the modelController to create the account and then telling one of its views/viewControllers to display the modal/whatever.
The usual way to pass data to a higher level is to have for the viewController/controller a delegate it uses to communicate with higher up, the one “responsible for actions the ViewController/controller cannot do by itself”, eg pushing data up(creation calls, modification calls, deletion calls) if it makes no sense to give it a modelController since its not control of that part of the application, etc. In your case you can of course pass a modelController to each little viewController/view, but its usually more practical/simpler to only give it to the one controlling the part and let others communicate with that currently-that-part-controlling controller/viewController.
More partical here means that you may not want CreateAccountViewController to display the success dialog, but rather another, which CreateAccountViewController can then do not by itself since it’s not on the stack anymore.
Related
I'm very new to programming.
I am trying to update an object in my Realm database but I get always an error.
I have tried to find the issue but I can't find anyone with a similar issue.
What I'm trying to do is:
I have a Game-Score-App.
It should display the names on Tab1 and on the Tab2 I want to give the user the ability, to change the names of the players. As soon as the ViewDidDisappear I want to write the changes to Realm.
I already figured out how to update the names in the database. And it works properly the first time.
But as soon as I go a second time on the Tab2 and go back to Tab1 again, I get the message "Primary key can't be changed after an object is inserted."
Any Ideas?
class Games: Object {
#objc dynamic var game_id = UUID().uuidString
#objc dynamic var gameName: String = ""
var playerNames = List<String>()
override class func primaryKey() -> String? {
return "game_id"
}
}
class FirstPageVC: UIViewController {
#IBOutlet var playerNameLabels: [UILabel]!
#IBOutlet weak var gameNameLabel: UILabel!
let realm = try! Realm()
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
let games = realm.objects(Games.self)
gameNameLabel.text = games[0].gameName
for i in 0...playerNameLabels.count - 1 {
playerNameLabels[i].text = games[0].playerNames[i]
}
}
}
class SecondPageVC: UIViewController {
#IBOutlet var playerNameTextbox: [UITextField]!
#IBOutlet weak var gameNameTextbox: UITextField!
#IBOutlet weak var numberOfIndex: UITextField!
let realm = try! Realm()
var playerNames: [String] = []
var gameName: String = ""
var game = Games()
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
if realm.objects(Games.self).count != 0 {
let games = realm.objects(Games.self)
gameNameTextbox.text = games[0].gameName
for i in 0...playerNameTextbox.count - 1 {
playerNameTextbox[i].text = games[0].playerNames[i]
}
}
}
#IBAction func addButton(_ sender: UIButton) {
gameName = gameNameTextbox.text!
for i in 0...playerNameTextbox.count - 1 {
playerNames.append(playerNameTextbox[i].text!)
}
let items = realm.objects(Games.self)
let number = Int(numberOfIndex.text!)
game.game_id = items[number!].game_id
game.gameName = gameName
game.playerNames.append(objectsIn: playerNames)
try! realm.write {
realm.add(game, update: .modified)
}
}
}
The problem is your Realm object structure. Anything that could possibly ever be changed should not be used as a primary key.
Also note from the Realm Documentation
Once an object with a primary key is added to a Realm, the primary key
cannot be changed.
To expand on that, it's often best practice to disassociate an objects key (e.g. primary key) from the rest of the properties of an object.
Here's how to do that
class Games: Object{
#objc dynamic var game_id = UUID().uuidString
#objc dynamic var gameName: String = ""
var playerNames = List<String>()
override class func primaryKey() -> String? {
return "game_id"
}
}
UUID().uuidString will generate a unique string for every object that's created and will look something like this string
CDEA69EA-AC84-4465-ABE3-DDA29D31B925
Once the object is created, you can use it to load that specific object or update it's properties.
See Objects with Primary Keys
Here's how to change the game name
let item = realm.object(ofType: Game.self, forPrimaryKey: "CDEA69EA-AC84-4465-ABE3-DDA29D31B925")!
try! realm.write {
game.gameName = "Pwn You!"
}
Try this solution:
Replace the code in viewDidDisappear after the end of for loop with the following code:
if let gameInRealm = realm.objects(Game.self).first{
try! realm.write {
gameInRealm.gameName = gameName
gameInRealm.playerNames = playerNames
}
}else{
game.gameName = gameName
game.playerNames.append(objectsIn: playerNames)
realm.add(game)
}
Explanation (if needed):
The code changes the existing Game properties in case a Game object exists. Otherwise, it creates a new one with the new properties.
Therefore, the else statement should get executed the first time you leave SecondPageVC, and then the if statement will get triggered every other time you leave SecondPageVC.
I am currently working on a project that has a Create Account page represented by a view controller called CreateNewAccount and a class of the same name which accompanies it. There are four values that are inputted into this view controller: 1) firstName, 2) lastName, 3) username, and 4) password. This view controller also has a "Create Account" button that when pressed, should transfer the String values inputted in the 4 inputs to a new class called UInfoRetrieveModel, which would be classified as a Model under the MVC configuration. Unfortunately this value transference part is not working.
I then have UInfoRetrieveModel pass these 4 values directly to another Model called UserInfo which then delegates out any of these values to other view controllers on the UI side that may need them displayed. I have figured out how to pass values from UInfoRetrieveModel to UserInfo and from UserInfo (which is a model) to said view controllers but I have not figured out how to pass from a view controller, specifically CreateNewAccount, to a model, which in this case is UInfoRetrieveModel.
Basically my idea here is to have two model classes: one model that receives (UInfoRetrieveModel) and one that delegates out (UserInfo) the data values set in CreateNewAccount, in order to make the transference of data across the UI more efficient.
Below is my code for CreateNewAccount and UInfoRetrieveModel, where the transference seems to not be working:
UInfoRetrieveModel->
import Foundation
protocol UInfoRetrieveModelDelegate: class {
func credentialTransfer(data:String)
}
class UInfoRetrieveModel: NSObject {
weak var delegate: UInfoRetrieveModelDelegate?
var firstName: String = ""
var lastName: String = ""
var userName: String = ""
var password: String = ""
func retrieving(){
delegate?.credentialTransfer(data: firstName)
delegate?.credentialTransfer(data: lastName)
delegate?.credentialTransfer(data: userName)
delegate?.credentialTransfer(data: password)
}
}
CreateNewAccount->
import UIKit
class CreateNewAccount: UIViewController{
#IBOutlet weak var FNInput: UITextField!
#IBOutlet weak var LNInput: UITextField!
#IBOutlet weak var usernameInput: UITextField!
#IBOutlet weak var passwordInput: UITextField!
var uInfoRetrieve = UInfoRetrieveModel()
#IBAction func thanksForJoining(_ sender: Any) {
uInfoRetrieve.firstName = FNInput.text!
uInfoRetrieve.lastName = LNInput.text!
uInfoRetrieve.userName = usernameInput.text!
uInfoRetrieve.password = passwordInput.text!
uInfoRetrieve.retrieving()
uInfoRetrieve.delegate = self
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension CreateNewAccount: UInfoRetrieveModelDelegate{
func credentialTransfer(data: String) {
print(data)
}
}
You are calling retrieving() in the wrong order. Use this order instead:
#IBAction func thanksForJoining(_ sender: Any) {
uInfoRetrieve.firstName = FNInput.text!
uInfoRetrieve.lastName = LNInput.text!
uInfoRetrieve.userName = usernameInput.text!
uInfoRetrieve.password = passwordInput.text!
uInfoRetrieve.delegate = self
uInfoRetrieve.retrieving()
}
Reason: If you call retreiving() before setting the delegate, the delegate will be nil and you won't get the callback.
Using the MVC approach for iOS app development, I would like to observe changes to the model by posting to the NotificationCenter. For my example, the Person.swift model is:
class Person {
static let nameDidChange = Notification.Name("nameDidChange")
var name: String {
didSet {
NotificationCenter.default.post(name: Person.nameDidChange, object: self)
}
}
var age: Int
var gender: String
init(name: String, age: Int, gender: String) {
self.name = name
self.age = age
self.gender = gender
}
}
The view controller that observes the model is shown below:
class ViewController: UIViewController {
let person = Person(name: "Homer", age: 44, gender: "male")
#IBOutlet weak var nameLabel: UILabel!
#IBOutlet weak var ageLabel: UILabel!
#IBOutlet weak var genderLabel: UILabel!
#IBOutlet weak var nameField: UITextField!
#IBOutlet weak var ageField: UITextField!
#IBOutlet weak var genderField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
nameLabel.text = person.name
ageLabel.text = String(person.age)
genderLabel.text = person.gender
NotificationCenter.default.addObserver(self,
selector: #selector(self.updateLabels),
name: Person.nameDidChange, object: nil)
}
#IBAction func updatePerson(_ sender: Any) {
guard let name = nameField.text, let age = ageField.text, let gender = genderField.text else { return }
guard let ageNumber = Int(age) else { return }
person.name = name
person.age = ageNumber
person.gender = gender
}
#objc func updateLabels() {
nameLabel.text = person.name
ageLabel.text = String(person.age)
genderLabel.text = person.gender
}
}
The example app works as follows:
Enter a name, age, and gender in the text fields
Press the updatePerson button to update the model from the text field values
When the model is updated, the notification observer calls the updateLabels function to update the user interface.
This approach requires the person.name to be set last otherwise the updatePerson button must be pressed twice to update the entire user interface. And since I'm only observing one property, the notification does not represent the entire class. Is there a better way to observe changes of models (a class or struct) in Swift?
Note - I am not interested in using RxSwift for this example.
This is more of a dumping comment than a fulfilling answer. But long story short KVO is the feature you should be using, not NotificationCenter. The binding process becomes significantly more simple in Swift4
As for what KVO is: See here and here. For some examples which are MVVM focused you can see here and here. And don't let the MVVM sway you away. It's just MVC with bindings which you are trying to do the exact same thing + moving the presentation logic to a different layer.
A simple KVO example in Swift 4 would look like this:
#objcMembers class Foo: NSObject {
dynamic var string: String
override init() {
string = "hotdog"
super.init()
}
}
let foo = Foo()
// Here it is, kvo in 2 lines of code!
let observation = foo.observe(\.string) { (foo, change) in
print("new foo.string: \(foo.string)")
}
foo.string = "not hotdog"
// new foo.string: not hotdog
You can also create your own Observable type like below:
class Observable<ObservedType>{
private var _value: ObservedType?
init(value: ObservedType) {
_value = value
}
var valueChanged : ((ObservedType?) -> ())?
public var value: ObservedType? {
get{
return _value // The trick is that the public value is reading from the private value...
}
set{
_value = newValue
valueChanged?(_value)
}
}
func bindingChanged(to newValue : ObservedType){
_value = newValue
print("value is now \(newValue)")
}
}
Then to create an observable property you'd do:
class User {
// var name : String <-- you normally do this, but not when you're creating as such
var name : Observable<String>
init (name: Observable<String>){
self.name = name
}
}
The class above (Observable) is copied and pasted from Swift Designs patterns book
To simply visualize the picture, you should be aware of the fact that you are observing only the name change. So it doesn't make sense to update all of the other properties of Person. You are observing name change and it's being updated accordingly, let alone others.
So it's not an ideal assumption that age and gender might have been changed in the process of changing name. Being said that, you should consider observing all of the properties one by one and bind actions differently and modify only the UI component that is mapped to that specific property.
Something like this:
override func viewDidLoad() {
...
NotificationCenter.default.addObserver(self,
selector: #selector(self.updateName),
name: Person.nameDidChange, object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(self.updateAge),
name: Person.ageDidChange, object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(self.updateGender),
name: Person.genderDidChange, object: nil)
...
}
#objc func updateName() {
nameLabel.text = person.name
}
#objc func updateAge() {
ageLabel.text = String(person.age)
}
#objc func updateGender() {
genderLabel.text = person.gender
}
I'm trying (unsuccessfully) to build a TreeController-controlled NSOutlineView. I've gone through a bunch of tutorials, but they all pre-load the data before starting anything, and this won't work for me.
I have a simple class for a device:
import Cocoa
class Device: NSObject {
let name : String
var children = [Service]()
var serviceNo = 1
var count = 0
init(name: String){
self.name = name
}
func addService(serviceName: String){
let serv = "\(serviceName) # \(serviceNo)"
children.append(Service(name: serv))
serviceNo += 1
count = children.count
}
func isLeaf() -> Bool {
return children.count < 1
}
}
I also have an even more simple class for the 'Service':
import Cocoa
class Service: NSObject {
let name: String
init(name: String){
self.name = name
}
}
Finally, I have the ViewController:
class ViewController: NSViewController {
var stepper = 0
dynamic var devices = [Device]()
override func viewDidLoad() {
super.viewDidLoad()
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
#IBAction func addDeviceAction(_ sender: Any) {
let str = "New Device #\(stepper)"
devices.append(Device(name: str))
stepper += 1
print("Added Device: \(devices[devices.count-1].name)")
}
#IBAction func addService(_ sender: Any) {
for i in 0..<devices.count {
devices[i].addService(serviceName: "New Service")
}
}
}
Obviously I have 2 buttons, one that adds a 'device' and one that adds a 'service' to each device.
What I can't make happen is any of this data show up in the NSOutlineView. I've set the TreeController's Object Controller Property to Mode: Class and Class: Device, and without setting the Children, Count, or Leaf properties I get (predictably):
2017-01-04 17:20:19.337129 OutlineTest[12550:1536405] Warning: [object class: Device] childrenKeyPath cannot be nil. To eliminate this log message, set the childrenKeyPath attribute in Interface Builder
If I then set the Children property to 'children' things go very bad:
2017-01-04 17:23:11.150627 OutlineTest[12695:1548039] [General] [ addObserver:forKeyPath:options:context:] is not supported. Key path: children
All I'm trying to do is set up the NSOutlineView to take input from the NSTreeController so that when a new 'Device' is added to the devices[] array, it shows up in the Outline View.
If anyone could point me in the right direction here I'd be most grateful.
Much gratitude to Warren for the hugely helpful work. I've got it (mostly) working. A couple of things that I also needed to do, in addition to Warren's suggestions:
Set the datastore for the Tree Controller
Bind the OutlineView to the TreeController
Bind the Column to the TreeController
Bind the TableView Cell to the Table Cell View (yes, really)
Once all that was done, I had to play around with the actual datastore a bit:
var name = "Bluetooth Devices Root"
var deviceStore = [Device]()
#IBOutlet var treeController: NSTreeController!
#IBOutlet weak var outlineView: NSOutlineView!
override func viewDidLoad() {
super.viewDidLoad()
deviceStore.append(Device(name: "Bluetooth Devices"))
self.treeController.content = self
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
#IBAction func addDeviceAction(_ sender: Any) {
if(deviceStore[0].name == "Bluetooth Devices"){
deviceStore.remove(at: 0)
}
Turns out the Root cannot be child-less at the beginning, at least as far as I can tell. Once I add a child, I can delete the place-holder value and the tree seems to work (mostly) as I want. One other thing is that I have to reload the data and redisplay the outline whenever the data changes:
outlineView.reloadData()
outlineView.setNeedsDisplay()
Without that, nothing. I still don't have the data updating correctly (see comments below Warren's answer) but I'm almost there.
To state the obvious, a NSTreeController manages a tree of objects all of which need to answer the following three questions/requests.
Are you a leaf i.e do you have no children? = leafKeyPath
If you are not a leaf, how many children do you have ? = countKeyPath
Give me your children! = childrenKeyPath
Its simple to set these up in IB or programatically. A fairly standard set of properties is respectively.
isLeaf
childCount
children
But its totally arbitrary and can be any set of properties that answer those questions.
I normally set up a protocol named something like TreeNode and make all my objects conform to it.
#objc protocol TreeNode:class {
var isLeaf:Bool { get }
var childCount:Int { get }
var children:[TreeNode] { get }
}
For your Device object you answer 2 out 3 question with isLeaf and children but don't answer the childCount question.
Your Device's children are Service objects and they answer none of that which is some of the reason why you are getting the exceptions.
So to fix up your code a possible solution is ...
The Service object
class Service: NSObject, TreeNode {
let name: String
init(name: String){
self.name = name
}
var isLeaf:Bool {
return true
}
var childCount:Int {
return 0
}
var children:[TreeNode] {
return []
}
}
The Device object
class Device: NSObject, TreeNode {
let name : String
var serviceStore = [Service]()
init(name: String){
self.name = name
}
var isLeaf:Bool {
return serviceStore.isEmpty
}
var childCount:Int {
return serviceStore.count
}
var children:[TreeNode] {
return serviceStore
}
}
And a horrible thing to do from a MVC perspective but convenient for this answer. The root object.
class ViewController: NSViewController, TreeNode {
var deviceStore = [Device]()
var name = "Henry" //whatever you want to name your root
var isLeaf:Bool {
return deviceStore.isEmpty
}
var childCount:Int {
return deviceStore.count
}
var children:[TreeNode] {
return deviceStore
}
}
So all you need to do is set the content of your treeController. Lets assume you have an IBOutlet to it in your ViewController.
class ViewController: NSViewController, TreeNode {
#IBOutlet var treeController:NSTreeController!
#IBOutlet var outlineView:NSOutlineView!
override func viewDidLoad() {
super.viewDidLoad()
treeController.content = self
}
Now each time you append a Device or add a Service just call reloadItem on the outlineView (that you also need an outlet to)
#IBAction func addDeviceAction(_ sender: Any) {
let str = "New Device #\(stepper)"
devices.append(Device(name: str))
stepper += 1
print("Added Device: \(devices[devices.count-1].name)")
outlineView.reloadItem(self, reloadChildren: true)
}
Thats the basics and should get you started but the docs for NSOutlineView & NSTreeController have a lot more info.
EDIT
In addition to the stuff above you need to bind your outline view to your tree controller.
First ensure your Outline View is in view mode.
Next bind the table column to arrangedObjects on the tree controller.
Last bind the text cell to the relevant key path. In your case it's name. objectValue is the reference to your object in the cell.
I have tried to implement the solution from this answer but I just haven't been able to get it to work. I get 'Use of unresolved identifier...' for the variables I am trying to access..
I have a loginViewController.swift that gets the username and password when someone logs in..
import UIKit
class loginViewController: UIViewController {
#IBOutlet weak var userEmailTextField: UITextField!
#IBOutlet weak var userPasswordTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func loginButtonTapped(sender: AnyObject) {
let userEmail = userEmailTextField.text;
let userPassword = userPasswordTextField.text;
Then I have a PostService.swift file that gets data from a MySQL database.. It should use the username of the person logged in to access the relevant data..
import Foundation
class PostService {
var settings:Settings!
let userEmail = "steve#centrix.co.za"; //This is hard coded but needs to come from the loginViewController
let userPassword = "1234"; //This is hard coded but needs to come from the loginViewController
I have tried that and a few other suggestions and I just don't seem to be able to get it to work.. Please help..
Thanks in advance.
You can just declare
var userEmail = "";
var userPassword = "";
outside a class (it doesn't matter which Swift class). Then, dropping the let,
#IBAction func loginButtonTapped(sender: AnyObject) {
userEmail = userEmailTextField.text;
userPassword = userPasswordTextField.text;
will store the variables, and you'll just be able to use the in the PostService class.
However, is there really no connection between the LoginViewController and the PostService? You'll have to call a PostService function somewhere ... maybe you can pass the variables there?