How can I print the variable of a singleton? - swift

import UIKit
class User: NSObject {
static let user = User()
private override init() {}
var id: String?
var name: String?
var email: String?
var profileImageUrl: String?
var profileImage: UIImage?
var profileImageDownloadUrl: String?
var partyStatus: Bool?
}
In my first viewcontroller I did:
override func viewDidLoad() {
super.viewDidLoad()
let user = User.user
user.name = "Bob"
}
In my second viewcontroller I did:
override func viewDidLoad() {
super.viewDidLoad()
let user = User.user
print(user.name)
}
I thought the second viewcontroller should print "Bob" but it returns as nil. What am I doing wrong?

Related

How to tell another view controller what song to play that is listed on a table view?

In my PlayerViewController, I am trying to play a song that is selected from my Table view. Also this first line of code is in another view controller. What would be a better way to write the player.playStream line?
EDIT: PlayerViewController
#IBOutlet weak var playPauseButton: UIButton!
var player: Player!
var song: [Song] = []
let indexPath = IndexPath()
var MusicPlayer: AVAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
player = Player()
setSession()
UIApplication.shared.beginReceivingRemoteControlEvents()
becomeFirstResponder()
NotificationCenter.default.addObserver(self, selector: Selector(("handleInterruption")), name: AVAudioSession.interruptionNotification, object: nil)
player.playStream(fileUrl: "http://127.0.0.1/musicfiles" + song[indexPath.row].getName())
changePlayButton()
}
Song.swift:
class Song {
var id = Int()
var name = String()
var year = Int()
var numLikes = Int()
var numPlays = Int()
init?(id:String, name:String, year:String, numlikes:String, numplays:String) {
self.id = Int(id)!
self.name = name
self.year = Int(year)!
self.numLikes = Int(numLikes)
self.numPlays = Int(numplays)!
}
func getId() -> Int {
return id
}
func getName() -> String {
return name
}
func getYear() -> Int {
return year
}
func getNumLikes() -> Int {
return numLikes
}
func getNumPlays() -> Int {
return numPlays
}
}

Swift MVVM Bind with Boxing

I am simply trying to create a weather application with WeatherViewController displaying the tableView with cells, and when the cell is tapped leads to WeatherDetailsViewController.
I am using the boxing way for binding and I am confused if I set Dynamic type in both the model and viewModel in the example below. You will know what I mean.
This is the Boxing Class
class Dynamic<T>: Decodable where T: Decodable {
typealias Listener = (T) -> ()
var listener: Listener?
var value: T {
didSet {
listener?(value)
}
}
func bind(listener: #escaping Listener) {
self.listener = listener
self.listener?(self.value)
}
init(_ value: T) {
self.value = value
}
private enum CodingKeys: CodingKey {
case value
}
}
This is the Weather Model Struct
struct Weather: Decodable {
let date: Dynamic<Int>
let description: Dynamic<String>
let maxTemperature: Dynamic<Double>
private enum CodingKeys: String, CodingKey {
case date = "time"
case description = "summary"
case maxTemperature = "temperatureMax"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
date = try Dynamic(container.decode(Int.self, forKey: .date))
description = try Dynamic(container.decode(String.self, forKey: .description))
maxTemperature = try Dynamic(container.decode(Double.self, forKey: .maxTemperature))
}
}
Here is my WeatherListViewModel & WeatherViewModel
Inside my WeatherViewModel I have assigned the type to be Dynamic but also in the model in order to bind in my WeatherDetailsViewController, is that right?
class WeatherListViewModel {
var weatherViewModels: [WeatherViewModel]
private var sessionProvider: URLSessionProvider
init(sessionProvider: URLSessionProvider) {
self.sessionProvider = sessionProvider
self.weatherViewModels = [WeatherViewModel]()
}
func numberOfRows(inSection section: Int) -> Int {
return weatherViewModels.count
}
func modelAt(_ index: Int) -> WeatherViewModel {
return weatherViewModels[index]
}
func didSelect(at indexPath: Int) -> WeatherViewModel {
return weatherViewModels[indexPath]
}
}
This is WeatherListViewModel Extension for network fetching where I initialize the WeatherViewModel
func fetchWeatherLocation(withLatitude latitude: CLLocationDegrees, longitude: CLLocationDegrees, completion: #escaping handler) {
sessionProvider.request(type: WeatherWrapper.self, service: WeatherService.specificLocation, latitude: latitude, longitude: longitude) { [weak self] result in
switch result {
case let .success(weatherWrapper):
let weathers = weatherWrapper.daily.weathers
self?.weatherViewModels = weathers.map {
return WeatherViewModel(weather: $0)
}
completion()
case let .failure(error):
print("Error: \(error)")
}
}
}
This is WeatherViewModel
struct WeatherViewModel {
private(set) var weather: Weather
var temperature: Dynamic<Double>
var date: Dynamic<Int>
var description: Dynamic<String>
init(weather: Weather) {
self.weather = weather
self.temperature = Dynamic(weather.maxTemperature)
self.date = Dynamic(weather.date)
self.description = Dynamic(weather.description)
}
}
Here is my WeatherDetailsViewController
Here I assign the binding to the labels respectively to get the changes
class WeatherDetailsViewController: UIViewController {
#IBOutlet private var imageView: UIImageView!
#IBOutlet private var cityLabel: UILabel!
#IBOutlet private var dateLabel: UILabel!
#IBOutlet private var descriptionLabel: UILabel!
#IBOutlet private var temperatureLabel: UILabel!
var viewModel: WeatherViewModel?
override func viewDidLoad() {
super.viewDidLoad()
setupVMBinding()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationItem.largeTitleDisplayMode = .never
}
private func setupVMBinding() {
if let viewModel = viewModel {
viewModel.date.bind {
self.dateLabel.text = $0.toString()
}
viewModel.temperature.bind {
self.temperatureLabel.text = "\($0)"
}
viewModel.description.bind {
self.descriptionLabel.text = $0.description
}
}
}
}
Question is, did I just repeat writing the type Dynamic in both model and viewModel? Is there a better way of doing this or am I on the right track. Sorry for the long code example.
I think you repeat writing Dynamic inside your Weather Model.
It does not need to be Dynamic type.
You can create a GenericDataSource
class GenericDataSource<T>: NSObject {
var data: Dynamic<T>?
}
Inside your View Model. This will Reference to your Weather Model without the need for creating dynamic type.
class WeatherViewModel {
var dataSource: GenericDataSource<Weather>?
....
}
Inside your View Controller
class WeatherDetailsViewController {
var viewModel: WeatherViewModel?
override func viewDidLoad() {
viewModel = ViewModel()
var dataSource = GenericDataSource<Weather>()
dataSource.data = Dynamic(Weather)
viewModel.dataSource = dataSource
setupVMBinding()
}
private func setupVMBinding() {
viewModel?.dataSource?.data?.bind {
self.dateLabel.text = $0.date
self.temperatureLabel.text = "\($0.maxTemperature)"
self.descriptionLabel.text = $0.description
}
}
}

Using Struct to pass a variable Swift

I'm trying to use a Struct to pass some variables that I get from a Facebook Graph Request such as email, name, gender, etc.
I've created the Struct ('fbDemographics') and the variables in 'ViewController' but I get an error when I try to call the struct and one of the variables in 'SecondViewController' (Type 'ViewController' has no member 'fbDemographics'). I've never used struct before so a bit baffled why I am getting this error. Thanks for any thoughts. The code for both view controllers is below:
class ViewController: UIViewController, FBSDKLoginButtonDelegate {
override func viewDidLoad() {
super.viewDidLoad()
struct fbDemographics {
static var relationship_status: String?
static var gender: String?
static var user_education_history: String?
static var user_location: String?
static var email: String?
static var name: String?
}
FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, relationship_status, gender, user_location, user_education_history, email"]).start(completionHandler: { (connection, result, error) -> Void in
if (error == nil){
//let fbDetails = result as! NSDictionary
//print(fbDetails)
if let userDataDict = result as? NSDictionary {
fbDemographics.gender = userDataDict["gender"] as? String
fbDemographics.email = userDataDict["email"] as? String
fbDemographics.name = userDataDict["name"] as? String
fbDemographics.user_location = userDataDict["user_location"] as? String
fbDemographics.user_education_history = userDataDict["user_education_history"] as? String
fbDemographics.relationship_status = userDataDict["relationship_status"] as? String
let myEducation = fbDemographics.user_education_history
let myEmail = fbDemographics.email
let myGender = fbDemographics.gender
let myName = fbDemographics.name
let myStatus = fbDemographics.relationship_status
let myLocation = fbDemographics.user_location
self.performSegue(withIdentifier: "LoginToHome", sender: (Any).self)
}
}
SECOND VIEW CONTROLLER
class SecondViewController: UIViewController {
#IBAction func verticalSliderChanged(_ sender: UISlider) {
let currentValue = String(sender.value);
sliderLabel.text = "\(currentValue)"
func viewDidLoad() {
super.viewDidLoad()
***ViewController.fbDemographics.myEmail***
}
}
The problem is that you've defined your struct inside viewDidLoad. So the scope is limited to that method. Move it out of viewDidLoad, but still in ViewController, and you should be able to access it from the SecondViewController. Obviously, you'll have to fix that reference to myEmail, too, because it's called email. Also, in your SecondViewController you should pull viewDidLoad implementation out of the verticalSliderChanged method; the viewDidLoad should be a top-level instance method of SecondViewController, not defined inside another method.
There are deeper problems here, though. Rather than using struct with static variables, you really should make those simple instance variables, create an instance of your FbDemographics type (note, start struct types with uppercase letter), and then pass this instance in prepare(for:sender:).
For example, the right way to pass data would be to:
eliminate static variables;
give your struct a name that starts with uppercase letter;
create instance of your struct; and
pass this instance to the destination view controller in prepare(for:sender:).
E.g.
struct FbDemographics {
var relationshipStatus: String?
var gender: String?
var userEducationHistory: String?
var userLocation: String?
var email: String?
var name: String?
}
class ViewController: UIViewController {
var demographics: FbDemographics?
override func viewDidLoad() {
super.viewDidLoad()
performRequest() // I actually don't think you should be initiating this in `viewDidLoad` ... perhaps in `viewDidAppear`
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? SecondViewController {
destination.demographics = demographics
}
}
func performRequest() {
FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, relationship_status, gender, user_location, user_education_history, email"]).start { connection, result, error in
guard let userDataDict = result as? NSDictionary, error == nil else {
print("\(error)")
return
}
self.demographics = FbDemographics(
relationshipStatus: userDataDict["relationship_status"] as? String,
gender: userDataDict["gender"] as? String,
userEducationHistory: userDataDict["user_education_history"] as? String,
userLocation: userDataDict["user_location"] as? String,
email: userDataDict["email"] as? String,
name: userDataDict["name"] as? String
)
self.performSegue(withIdentifier: "LoginToHome", sender: self)
}
}
}
And then SecondViewController could:
class SecondViewController: UIViewController {
var demographics: FbDemographics!
override func viewDidLoad() {
super.viewDidLoad()
let value = demographics.email // this should work fine here
}
}

I want to observe when a value has been changed, and to load the view

//Patient class
import Foundation
struct Patients {
var family: NSArray
var given: NSArray
var id: String
var birthdate:String
var gender: String
}
struct Address {
var city: String
var country: String
var line: NSArray
}
class Patient {
var flag = 0
var address = Address(city: "", country: "", line: [""])
var patient_info = Patients(family: [""], given: [""], id: "", birthdate: "", gender: "")
var response : AnyObject?
init(response: AnyObject) {
self.response = response
if let entry = response.objectForKey("entry") {
//MARK: Address
if let resource = entry[0].objectForKey("resource") {
if let add = resource.objectForKey("address") {
address.city = add[0].objectForKey("city")! as! String
address.country = add[0].objectForKey("country")! as! String
address.line = add[0].objectForKey("line")! as! NSArray
//MARK: patient
patient_info.birthdate = resource.objectForKey("birthDate")! as! String
patient_info.gender = resource.objectForKey("gender")! as! String
if let name = resource.objectForKey("name") {
patient_info.family = name[0].objectForKey("family")! as! NSArray
patient_info.given = name[0].objectForKey("given")! as! NSArray
}
}
}
//MARK: id
if let link = entry[0].objectForKey("link") {
if let url = link[0].objectForKey("url") {
let id = url.componentsSeparatedByString("/")
patient_info.id = id[id.count-1]
}
}
}
print(patient_info)
}
}
//ViewController class
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
var viewModel = ViewModel()
#IBOutlet weak var family_name: UITextField!
#IBOutlet weak var given_name: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
family_name.delegate = self
given_name.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
switch textField {
case family_name:
family_name.resignFirstResponder()
given_name.becomeFirstResponder()
case given_name:
given_name .resignFirstResponder()
default:
print("")
}
return true
}
#IBAction func search(sender: UIButton) {
let family_name1 = family_name.text!
let given_name1 = given_name.text!
viewModel .searchForPatient(family_name1, given_name: given_name1)
//When the name property from my patient class changed I can call the //below method. How to implement the observer?
performSegueWithIdentifier("showSegue", sender:sender)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender:AnyObject?){
if segue.identifier == "showPatientSegue" {
if let displayViewController = segue.destinationViewController as? DisplayViewController {
displayViewController.viewModelDisplay.patient = viewModel.patient
}
}
}
}
// ViewModel where I make the request.
import Foundation
import Alamofire
import SystemConfiguration
class ViewModel {
var patient = Patient!()
func searchForPatient(family_name: String, given_name : String) {
let header = ["Accept" : "application/json"]
Alamofire.request(.GET, "https://open-ic.epic.com/FHIR/api/FHIR/DSTU2/Patient?family=\(family_name)&given=\(given_name)", headers: header).responseJSON { response in
self.patient = Patient(response: response.result.value!)
}
}
func checkInternetConnection() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}
var flags = SCNetworkReachabilityFlags()
if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
return false
}
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
return (isReachable && !needsConnection)
}
}
The problem is that the view loads fester than the request and I need to observe when a property has been changed in my Patient class, so the view can be loaded. If the view loads faster than the request I can't display the Patient information which I need.
You have lots options:
Store a delegate (weak!) object to the ViewController so that when your patient finishes, you can load the view. In the meantime, display something sensible in the view instead.
Send an NSNotification out, which the ViewController is a listener for.
KVO (Explanation of it here, just search for 'key-value observing'), which would require your Patient object to extend NSObject so that you can leverage objc's KVO.
Hope that helps!
You can add an observer on your variable this way :
var yourVariable:String!{
didSet{
refreshView()
}
}

I want to create a function which can return the responseJson and use it to create some objects in init

import UIKit
import Alamofire
class ViewController: UIViewController {
#IBOutlet weak var uiNameSearch: UITextField!
#IBOutlet weak var uiGivenName: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func searchForName(sender: UIButton) {
let header = ["Accept" : "application/json"]
let name = uiNameSearch.text!
let given = uiGivenName.text!
Alamofire.request(.GET, "https://open-ic.epic.com/FHIR/api/FHIR/DSTU2/Patient?family=\(name)&given=\(given)", headers: header).responseJSON { response in
let patient = response.result.value!
if let entry = patient.objectForKey("entry") {
if let link = entry[0].objectForKey("link") {
if let url = link[0].objectForKey("url") {
let fullNameArr = url.componentsSeparatedByString("/")
print(fullNameArr[fullNameArr.count-1])
}
//print(link)
}
}
}
}
}
My Patient class is:
class Patient {
var name: String
var given: String
var id: String
init(name: String, given: String, id: String) {
}
}
I want to use the response in init to create objects, how can I do this?