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

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?

Related

How to make a correct authorization

i am making an app Redmine, i have a website with a user with pass and there are issues. But i can't understand what i should do to make authorization.
Here I have Router, Request, AuthViewController. I also wanted to ask how i have to make AuthRequest? What has to be there?
AuthViewController
import UIKit
class AuthViewController: UIViewController {
#IBOutlet weak var emailField: UITextField!
#IBOutlet weak var passwordField: UITextField!
#IBOutlet weak var signInBotton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func signInDidTap(_ sender: Any) {
login()
}
fileprivate func login(){
AuthRequest.login(email: emailField.text!, password: passwordField.text!){(user, error) in DispatchQueue.main.async {
[unowned self] in self.openIssues()
}
}
}
}
//extension AuthViewController: Router{
// func prepare() {
// Here error with 'seque' if(seque.identifier = Seque.issues.rawValue){
// print("It's OK")
// guard let controller = seque.destination as? IssuesViewController else { print("Wrong destination"); return}
// //controller.presenter = IssuesPresenter();
// }
// }
//
// func openIssues() {
// print("kek")
// }
//
//
// enum Seque: String {
// case issues = "IssuesSeque"
// }
//
//}
There is also an error in if-block in extension.

Cannot pass data to a label with delegation

My console prints: "ModelToControllerDelegate.Model".
import Foundation
class Model {
let firstName: String
let lastName: String
init(firstName: String, lastName: String) {
self.firstName = firstName
self.lastName = lastName
}
}
import Foundation
protocol DataModelDelegate: class {
func didRecievedDataUpdate(data: Model)
}
class ModelController {
weak var delegate: DataModelDelegate?
func requestData() {
let data = Model(firstName: "Jack", lastName: "Johnson")
delegate?.didRecievedDataUpdate(data: data)
}
}
import UIKit
class ViewController: UIViewController {
let modelController = ModelController()
#IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
modelController.delegate = self
modelController.requestData()
}
}
extension ViewController: DataModelDelegate {
func didRecievedDataUpdate(data: Model) {
print(data)
}
}
Add In
extension ViewController: DataModelDelegate {
func didRecievedDataUpdate(data: Model) {
print(data) // data is object of class Model so output is"ModelToControllerDelegate.Model"
print(data.firstName) // firstName is String so Output is Jack
print(data.lastName) // lastName is String so Output is Johnson
}
}

URL validation not working in swift

started learning swift two weeks ago, with no previous programming experience, and I can't for the life of me figure out why this wouldn't work to check for nil. it just crashes when trying to load a web page if the user enters an invalid URL. This is the ENTIRETY of the code.
import UIKit; import WebKit
class ViewController: UIViewController {
#IBOutlet weak var adressBar: UITextField!
#IBOutlet weak var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func returnPressed(_ sender: Any) {
if let adressBarText = adressBar.text {
if let myURL = URL(string: adressBarText) {
let myRequest = URLRequest(url: myURL)
webView.load(myRequest)
adressBar.resignFirstResponder()
print("EYYYYY")
} else {
print("BOOOO")
}
}
}
}
Try this method
func verifyUrl (urlString: String?) -> Bool {
//Check for nil
if let urlString = urlString {
// create NSURL instance
if let url = NSURL(string: urlString) {
// check if your application can open the NSURL instance
return UIApplication.sharedApplication().canOpenURL(url)
}
}
return false
}
https://stackoverflow.com/a/30130535/8069241

Variable error in Swift code

I have an Xcode project which has some error. I had only a problem with a variable. I convert the txt string variable to int and this called txtint. When I want to make an calculation I can't because it has null value what is impossible because I give a value in function "pass" and then when I want to subtract I can't because txtint has null value.
//
// ViewController.swift
// Biophere
//
// Created by Coder on 2017. 10. 22..
// Copyright © 2017. Pliz Help. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var label: UILabel!
#IBOutlet weak var textview: UITextField!
#IBOutlet weak var conv: UILabel!
var text: String? = nil
var txt: String? = nil
var convert: String? = nil
var textint: Int? = nil
var txtint: Int? = nil
#IBAction func pass(_ sender: Any) {
var txt: String {
get {
return textview.text ?? ""
}
set {
textview.text = newValue
}
}
//conv.text = txt
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
label.text = text
txt = textview.text
}
#IBAction func saveButton(_ sender: Any) {
let textint = Int(text!)
let txtint = Int(txt!)
convert = String(textint! - txtint!)
conv.text = txt
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
ERROR: Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
var text: String = ""
var txt: String = ""
var convert: String = ""
var textint: Int = 0
var txtint: Int = 0
#IBAction func saveButton(_ sender: Any) {
if let textint = Int(text), let txtint = Int(txt) {
convert = String(textint - txtint)
conv.text = txt
}else{
print("handle it")
}
}
Suggestion: Try to give variable name descriptive it is a basic thing for development.

Changing the view color when comparing values

I created a view to use as background and I would like to change its color when label text is greater or less than variable number. The script is okay but the color is not changing.
Thanks in advance.
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var localName: UITextField!
#IBOutlet weak var localNameLabel: UILabel!
#IBOutlet weak var localTemp: UILabel!
#IBAction func getData(sender: AnyObject) {
getWeatherData("http://api.openweathermap.org/data/2.5/weather?q=" + localName.text! + "")
}
#IBOutlet weak var fundo: UIView!
override func viewDidLoad() {
super.viewDidLoad()
getWeatherData("http://api.openweathermap.org/data/2.5/weather?q=London")
// 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.
}
func getWeatherData(urlString: String){
let url = NSURL (string: urlString)
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, response, error) in
dispatch_async(dispatch_get_main_queue(), {
self.setLabels(data!)
})
}
task.resume()
}
func setLabels(weatherData: NSData) {
do {
let json = try NSJSONSerialization.JSONObjectWithData(weatherData, options:NSJSONReadingOptions.MutableContainers) as! NSDictionary
print(json)
//localNameLabel.text = json[("name")] as? String
if let name = json[("name")] as? String {
localNameLabel.text = name
}
if let main = json[("main")] as? NSDictionary {
if let temp = main[("temp")] as? Double {
//convert kelvin to celsius
let ft = (temp - 273.15)
let myString = ft.description
localTemp.text = myString
self.changeColor()
}
}
} catch let error as NSError {
print(error)
}
var number : Float
func changeColor(){
number = 19.0
if(Float(localTemp.text!) < number){
fundo.backgroundColor = .blueColor()
}else{
fundo.backgroundColor = .orangeColor()
}
}
}
}
Edited to post the entire script
In your view controller you need to add UITextFieldDelegate which will allow you to access methods related to your text field. The top of your view controller should look like this:
class ViewController: UIViewController,UITextFieldDelegate //set delegate to class
You then need to set the delegate of your text field to self in viewDidLoad and add a target for when the text field changes:
override func viewDidLoad() {
super.viewDidLoad()
localTemp.delegate = self //set delegate to this vc
localTemp.addTarget(self, action: "textFieldDidChange:", forControlEvents: UIControlEvents.EditingChanged)
}
You can then implement this method which will run on every key press and you need to call your changeColor() method as above:
func textFieldDidChange(textField: UITextField) {
self.changeColor()
}