How can i passing data uiviewController from uiview
I am Using function but it was not working
protocol name is startcalldelegate and function name is startcall
UIView Code
protocol StartCallDelegate: class {
func startCall(localNickname :String, remoteNickname :String)}
class CardView: UIView {
let managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
weak var delegate: CardViewDelegate?
weak var socketdelegate: StartCallDelegate?
#IBOutlet weak var UserPhoto: UIImageView!
#IBOutlet weak var UserNickName: UILabel!
#IBOutlet weak var UserAge: UILabel!
#IBOutlet weak var UserPeople: UILabel!
var localNickname: String = ""
var remoteNickname: String = ""
#IBAction func SendMessage(_ sender: Any) {
print("SendMessage")
//print(localNickName)
//print(UserNickName.text!)
}
#IBAction func SendVideoCall(_ sender: Any) {
print("SendVideoCall")
let entityDescription = NSEntityDescription.entity(forEntityName: "Profile", in: managedObjectContext)
let request = NSFetchRequest<NSFetchRequestResult>()
request.entity = entityDescription
do {
let objects = try managedObjectContext.fetch(request)
if objects.count > 0 {
let match = objects[0] as! NSManagedObject
localNickname = match.value(forKey: "nick") as! String
} else {
print("Nothing founded")
}
} catch {
print("error")
}
remoteNickname = UserNickName.text!
socketdelegate?.startCall(localNickname: localNickname, remoteNickname: remoteNickname)
delegate?.VideoChatSegue()
}
}
UIViewcontroller Code
class ViewController: UIViewcontroller, StartCallDelegate {
var localNickname: String = ""
var remoteNickname: String = ""
override func viewDidLoad() {
super.viewDidLoad()
print(localNickname)
print(remoteNickname)
}
func startCall(localNickname: String, remoteNickname: String) {
print("Action startcall func")
self.localNickname = localNickname
self.remoteNickname = remoteNickname
}
startCall func not working
You need to define delegate in viewcontroller' ViewDidLoad
let objOardView = CardView() // this is only test purpose
objOardView.socketdelegate = self
Related
I'm trying to make a quiz application using the API, I can take api data and show on app but I cannot transfer data from extension in viewController to button pressed.right now, when click the button, I want the clicked option to be green or red, how can I do it?
QuizManager
import Foundation
protocol quizManagerDelegate {
func didUpdateQuiz(_ Quizmanager: QuizManager ,quiz: QuizModel)
}
struct QuizManager {
var delegate: quizManagerDelegate?
func performRequest(){
let urlString = "https://opentdb.com/api.php?amount=1&type=multiple"
if let url = URL(string: urlString){
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url) { data, response, error in
if error != nil {
print(error!)
return
}
if let safeData = data{
if let quiz = self.parseJSON(quizdata: safeData){
delegate?.didUpdateQuiz(self, quiz: quiz)
}
}
}
task.resume()
}
}
func handle(data: Data?, response: URLResponse?, error: Error?) -> Void {
}
func parseJSON(quizdata: Data) -> QuizModel? {
let decoder = JSONDecoder()
do{
let decodedData = try decoder.decode(Welcome.self, from: quizdata)
let correct = decodedData.results?[0].correct_answer ?? "error"
let quest = decodedData.results?[0].question ?? "error"
let incorrect = decodedData.results?[0].incorrect_answers ?? ["error"]
let question = QuizModel(correctAnswer: correct, question: quest, falseAnswer: incorrect)
return question
} catch {
print(error)
return nil
}
}
}
QuizData
import Foundation
// MARK: - Welcome
struct Welcome: Codable {
let results: [Result]?
}
// MARK: - Result
struct Result: Codable {
let category: String?
let question, correct_answer: String?
let incorrect_answers: [String]?
}
QuizModel
import Foundation
struct QuizModel {
let correctAnswer : String
let question : String
let falseAnswer : [String]
}
ViewController
import UIKit
import GameKit
class ViewController: UIViewController {
#IBOutlet weak var ChoiceButton4: UIButton!
#IBOutlet weak var ChoiceButton3: UIButton!
#IBOutlet weak var ChoiceButton2: UIButton!
#IBOutlet weak var ChoiceButton1: UIButton!
#IBOutlet weak var QuestionTextView: UITextView!
var quizMangager = QuizManager()
#IBAction func OptionsButtonPressed(_ sender: UIButton) {
}
override func viewDidLoad() {
super.viewDidLoad()
QuestionTextView.layer.cornerRadius = 15
quizMangager.delegate = self
quizMangager.performRequest()
}
}
extension ViewController : quizManagerDelegate{
func didUpdateQuiz(_ Quizmanager: QuizManager, quiz: QuizModel) {
DispatchQueue.main.async { [self] in
self.QuestionTextView.text = quiz.question
var allOptions = []
allOptions.append(quiz.falseAnswer[0])
allOptions.append(quiz.falseAnswer[1])
allOptions.append(quiz.falseAnswer[2])
allOptions.append(quiz.correctAnswer)
let generatedValue = Array(allOptions.shuffled().prefix(4))
print(generatedValue)
print(quiz.correctAnswer)
ChoiceButton1.setTitle(generatedValue[0] as? String, for: .normal)
ChoiceButton2.setTitle(generatedValue[1] as? String, for: .normal)
ChoiceButton3.setTitle(generatedValue[2] as? String, for: .normal)
ChoiceButton4.setTitle(generatedValue[3] as? String, for: .normal)
}
}
}
ViewController
import UIKit
import GameKit
class ViewController: UIViewController {
#IBOutlet weak var ChoiceButton4: UIButton!
#IBOutlet weak var ChoiceButton3: UIButton!
#IBOutlet weak var ChoiceButton2: UIButton!
#IBOutlet weak var ChoiceButton1: UIButton!
#IBOutlet weak var QuestionTextView: UITextView!
var quizMangager = QuizManager()
#IBAction func OptionsButtonPressed(_ sender: UIButton) {
}
override func viewDidLoad() {
super.viewDidLoad()
QuestionTextView.layer.cornerRadius = 15
quizMangager.delegate = self
quizMangager.performRequest()
}
}
extension ViewController : quizManagerDelegate{
func didUpdateQuiz(_ Quizmanager: QuizManager, quiz: QuizModel) {
DispatchQueue.main.async { [self] in
self.QuestionTextView.text = quiz.question
var allOptions = []
allOptions.append(quiz.falseAnswer[0])
allOptions.append(quiz.falseAnswer[1])
allOptions.append(quiz.falseAnswer[2])
allOptions.append(quiz.correctAnswer)
let generatedValue = Array(allOptions.shuffled().prefix(4))
print(generatedValue)
print(quiz.correctAnswer)
ChoiceButton1.setTitle(generatedValue[0] as? String, for: .normal)
ChoiceButton2.setTitle(generatedValue[1] as? String, for: .normal)
ChoiceButton3.setTitle(generatedValue[2] as? String, for: .normal)
ChoiceButton4.setTitle(generatedValue[3] as? String, for: .normal)
}
}
}
You need to "hold onto the quiz data."
So, add a var property to your view controller:
var quizMangager = QuizManager()
// add this
var theQuiz: QuizModel?
then, in your didUpdateQuiz func, set that property:
func didUpdateQuiz(_ Quizmanager: QuizManager, quiz: QuizModel) {
DispatchQueue.main.async { [self] in
// add this
self.theQuiz = quiz
self.QuestionTextView.text = quiz.question
// ... no other changes
Now, connect all your buttons to #IBAction func OptionsButtonPressed and try this:
#IBAction func OptionsButtonPressed(_ sender: UIButton) {
guard let thisQuiz = theQuiz,
let btnTitle = sender.currentTitle
else { return }
if btnTitle == thisQuiz.correctAnswer {
sender.setTitleColor(.systemGreen, for: [])
} else {
sender.setTitleColor(.systemRed, for: [])
}
}
I have my upload code here
import UIKit
import Firebase
class ChatViewController: UIViewController {
let chatRef = FIRDatabase.database().reference().child("chat")
let userUid = FIRAuth.auth()?.currentUser?.uid
var userName = ""
#IBOutlet weak var topBar: UINavigationItem!
#IBOutlet weak var containerView: UIView!
#IBOutlet var inputTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
topBar.title = "Chat Log Controller"
FIRDatabase.database().reference().child("users/\(userUid!)/name").observe(.value) { (snap: FIRDataSnapshot) in
self.userName = (snap.value! as! String).description
}
}
#IBAction func handleSend(_ sender: AnyObject) {
let childChatRef = chatRef.childByAutoId()
let message = inputTextField.text!
childChatRef.child("text").setValue(message)
print(inputTextField.text)
}
#IBAction func handleSendByEnter(_ sender: AnyObject) {
let childChatRef = chatRef.childByAutoId()
let message = inputTextField.text!
print(userName)
childChatRef.child("name").setValue(userName)
childChatRef.child("text").setValue(message)
print(inputTextField.text)
}
}
text is successfully uploaded But
It doesn't print userName and doesn't upload it to Firebase Database
But username is nut nil!
Try to use your observer code as,
ref.observeSingleEventOfType(.Value, withBlock: { snapshot in
}
Just take self.username = snap.value! as! String
It will solve your problem.
Sorry for my English.
I have many problems in achieving data persistence after call the webservice .
Everything works correctly but I need to use that data in other methods .
As seen in the image once charge data on the screen then I want to give the user the option to use them well or load new data . But not as saving the data recovery webservice .
I was trying to use NSUserDefault but neither work .
From already thank you very much , any response is helpful .
Regards!
ViewController:
class ViewController: UIViewController {
let defaults = NSUserDefaults.standardUserDefaults()
#IBOutlet weak var myLabel2: 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.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let newVC : SecondViewController = segue.destinationViewController as! SecondViewController
let telefono = myLabel2.text!
newVC.recibirString = telefono
}
#IBAction func mostrarAlgo(sender:AnyObject) {
//something
}
}
SecondViewController:
class SecondViewController: UIViewController {
let defaults = NSUserDefaults.standardUserDefaults()
var tel: String = ""
#IBOutlet weak var myLabel1: UITextField!
#IBOutlet weak var myLabel3: UITextField!
#IBOutlet weak var myLabel4: UITextField!
#IBOutlet weak var myLabel5: UITextField!
#IBOutlet weak var myLabel6: UITextField!
#IBOutlet weak var myLabel7: UITextField!
#IBOutlet weak var myLabel8: UITextField!
var recibirString = String()
override func viewDidLoad() {
super.viewDidLoad()
myLabel1.text = recibirString
performRequestAndUpdateUI2(myLabel1.text!)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func performRequestAndUpdateUI2(tel:String) {
WebService.llamarWebService (tel,completionHandler: { datos in
guard datos.count == 5 else {
self.myLabel8.text = ("El número ingresado no está registrado.")
return
}
guard datos[0] as! String == "OK" else {
print("not everything was OK")
return
}
dispatch_async(dispatch_get_main_queue()) {
self.myLabel3.text = datos[0] as? String
self.myLabel4.text = datos[1] as? String
self.myLabel5.text = datos[2] as? String
self.myLabel6.text = datos[3] as? String
self.myLabel7.text = datos[4] as? String
self.myLabel8.text = ("Usted está registrado.")
//need save this data
}
})
}
#IBAction func guardarDatos(sender: AnyObject) {
// do something
}
}
WebService:
class WebService{
var telefono = ""
class func llamarWebService(telefono:String, completionHandler: (datos:NSArray)->()){
let urlPath = "http://xxxxxxxxxxx.com.ar/xxxxxxxxxx/forwarder_number?phone=\(telefono)"
let url = NSURL(string: urlPath)
let session = NSURLSession.sharedSession()
var arreglo:NSArray!
let task = session.dataTaskWithURL(url!,completionHandler: {data,response,error -> Void in
if (error != nil){
print(error?.localizedDescription)
}
let nsdata: NSData = NSData(data: data!)
arreglo = self.retornarDatos(nsdata)
completionHandler(datos: arreglo)
})
task.resume()
}
class func retornarDatos(nsdata: NSData)-> Array<String>{
let datos = NSString(data:nsdata,encoding: NSUTF8StringEncoding)
let partes = datos?.componentsSeparatedByString(",")
var arreglo : [String] = []
for i in partes!{
arreglo.append(i)
}
return arreglo
}
}
Usually Alamofire working nice with simple urls like:
"http://somesite.com/folder/file.json"
But when I use:
"http://somesite.com/folder/(jsonName.text).json
it always give me a nil... jsonName is a TextField as well...
That's the whole Controller:
import UIKit
import CoreLocation
import Alamofire
import SwiftyJSON
import CoreData
typealias CompletionHandler = (obj:AnyObject?, error:Bool?) -> Void
class LoginViewController: UIViewController, UITabBarControllerDelegate, UITextFieldDelegate, NSURLConnectionDelegate {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
#IBOutlet weak var wePrepareQuestLabel: UILabel!
#IBOutlet weak var downQuestProgres: UIActivityIndicatorView!
#IBOutlet weak var doNotCloseAppLabel: UILabel!
#IBOutlet weak var loginBgImage: UIImageView!
#IBOutlet weak var EmptyCodeError: UILabel!
#IBOutlet weak var loginTabBarItem: UITabBarItem!
#IBOutlet weak var QuestCodeTextField: UITextField!
#IBOutlet weak var loginTextFieldImage: UIImageView!
#IBOutlet weak var downloaded: UIButton!
#IBOutlet weak var createQuestButton: UIButton!
#IBAction func createQuest(sender: UIButton) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("WebViewController") as! UIViewController
self.presentViewController(vc, animated: true, completion: nil)
}
let Path: String = ""
#IBAction func QuestFetchButton(button: UIButton) {
if QuestCodeTextField.text.isEmpty {
EmptyCodeError.hidden = false
}
else if IJReachability.isConnectedToNetwork() {
}
else
{
QuestCodeTextField.hidden = true
button.hidden = true
EmptyCodeError.hidden = true
createQuestButton.hidden = true
doNotCloseAppLabel.hidden = false
wePrepareQuestLabel.hidden = false
loginTextFieldImage.hidden = true
downQuestProgres.hidden = false
self.downloaded.hidden = false
// questDownloadSaveJSON()
var objThisVC = LoginViewController()
objThisVC.callAndGetResponse { (obj, error) -> Void in
if (obj != nil) {
self.setUpDataInCoreData(obj)
print("ALL DIE")
self.performSegueWithIdentifier("QuestsListViewController", sender: nil)
}
else {
println("Response nil!!")
}
}
}
}
var file:NSFileHandle?
var pathURL: NSURL
{
let folder = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String
let path = folder.stringByAppendingPathComponent("\(QuestCodeTextField.text).json")
let url = NSURL(fileURLWithPath: path)
return url!
}
var code: String = ""
override func viewDidLoad() {
super.viewDidLoad()
QuestCodeTextField.text = code
self.QuestCodeTextField.delegate = self;
}
func setUpDataInCoreData(obj:AnyObject?){
println("Web Serviece Response \(obj)")
let dirEvent = obj as! NSDictionary
var aryEvent = dirEvent.valueForKey("events") as! NSArray
var indexEvent : Int = 0;
for (dirContent) in aryEvent
{
// Create Event Instance
var newItem: Events = NSEntityDescription.insertNewObjectForEntityForName("Events", inManagedObjectContext: self.appDelegate.cdh.backgroundContext!) as! Events
newItem.title = dirContent.valueForKey("title") as! String
newItem.indexID = String(indexEvent++) as String
println(newItem.title)
println(newItem.indexID)
var indexContent : Int = 0;
var aryContent = dirContent.valueForKey("content") as! NSArray
for (dirContentDetail) in aryContent{
var contentEntity: Content = NSEntityDescription.insertNewObjectForEntityForName("Content", inManagedObjectContext: self.appDelegate.cdh.backgroundContext!) as! Content
contentEntity.content_type = dirContentDetail.valueForKey("content_type") as! String
contentEntity.visible = dirContentDetail.valueForKey("visible") as! Bool
contentEntity.indexID = String(indexContent++) as String
println(contentEntity.content_type)
println(contentEntity.visible)
if contentEntity.content_type == "text"{
contentEntity.data_type = dirContentDetail.valueForKey("data") as! String
}
else if contentEntity.content_type == "image" || contentEntity.content_type == "audio" || contentEntity.content_type == "video" || contentEntity.content_type == "choice" {
contentEntity.data_type = ""
if (dirContentDetail.valueForKey("data") != nil && dirContentDetail.valueForKey("data")?.count>0 )
{
var indexImage : Int = 0;
var aryDTImages = dirContentDetail.valueForKey("data") as! NSArray
if aryDTImages.count > 0 {
for strContentDetail in aryDTImages as! [String]{
var objDtImg : DataTypeImage = NSEntityDescription.insertNewObjectForEntityForName("DataTypeImage", inManagedObjectContext: self.appDelegate.cdh.backgroundContext!) as! DataTypeImage
var strURL : NSString = NSString(string: strContentDetail)
objDtImg.urlString = strURL as String
objDtImg.indexID = String(indexImage++) as String
objDtImg.dtImages = contentEntity
// her have to set image to content
contentEntity.content = newItem
}
}
}
}
// here have to set entity to content
contentEntity.content=newItem
}// this is the end of content for loop
}// end of aryEvent
// here to save statement
self.appDelegate.cdh.saveContext(self.appDelegate.cdh.backgroundContext!)
// self.table.reloadData()
}
func callAndGetResponse(complitionHandler : CompletionHandler){
complitionHandler(obj: nil, error: true)
Alamofire.request(.GET, "http://g57732cr.bget.ru/\(QuestCodeTextField.text).json").responseJSON() {
(_, _, data, error) in
if error == nil {
complitionHandler(obj: data, error: false)
}
else{
complitionHandler(obj: nil, error: true)
self.performSegueWithIdentifier("QuestsListViewController", sender: nil)
}
// Fetch all data from Core Data
//self.fetchAllData()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Hide keyboard by tap on the rest of the view
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
view.endEditing(true)
}
//ReturnButton hides keyboard
func textFieldShouldReturn(textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "QuestsListViewController"){
var destination = segue.destinationViewController as! UINavigationController
let VC = destination.topViewController as! QuestListViewController
VC.questCode = self.QuestCodeTextField.text
}
}
}
So, this is my code:
ViewController 1 :
class ViewSet: UIViewController {
#IBOutlet var Label_1: UILabel!
#IBOutlet var Label_2: UILabel!
#IBOutlet var Text: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
var moc: NSManagedObjectContext = appDel.managedObjectContext!
var request = NSFetchRequest(entityName: "TestingCoreData")
request.returnsObjectsAsFaults = false;
var results: NSArray = moc.executeFetchRequest(request, error: nil)!
if (results.count > 0) {
var res = results[0] as! NSManagedObject
Label_1.text = res.valueForKey("label_1") as? String
Label_2.text = res.valueForKey("label_2") as? String
Text.text = res.valueForKey("text") as? String
} else {
println("No results found")
}
}
}
ViewController 2:
import UIKit
import CoreData
class Label_1: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
#IBOutlet var Label_1: UITextField!
#IBAction func addLabel_1(sender: AnyObject) {
var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
var moc: NSManagedObjectContext = appDel.managedObjectContext!
var label1 = NSEntityDescription.insertNewObjectForEntityForName("TestingCoreData", inManagedObjectContext: moc) as! NSManagedObjectContext
label1.setValue("\(Label_1.text)", forKey: "label_1")
moc.save(nil)
println("Object saved")
performSegueWithIdentifier("toLabel2", sender: self)
}
}
ViewController 3:
import UIKit
import CoreData
class Label_2: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
#IBOutlet var Label_2: UITextField!
#IBAction func add(sender: AnyObject) {
var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
var moc: NSManagedObjectContext = appDel.managedObjectContext!
var label2 = NSEntityDescription.insertNewObjectForEntityForName("TestingCoreData", inManagedObjectContext: moc) as! NSManagedObjectContext
label2.setValue("\(Label_2.text)", forKey: "label_2")
moc.save(nil)
println("Object saved")
performSegueWithIdentifier("toText", sender: self)
}
}
ViewController 4:
import UIKit
import CoreData
class Text: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
#IBOutlet var Text: UITextView!
#IBAction func done(sender: AnyObject) {
var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
var moc: NSManagedObjectContext = appDel.managedObjectContext!
var text = NSEntityDescription.insertNewObjectForEntityForName("TestingCoreData", inManagedObjectContext: moc) as! NSManagedObjectContext
text.setValue("\(Text.text)", forKey: "text")
moc.save(nil)
println("Object saved")
navigationController?.popToRootViewControllerAnimated(true)
}
}
I believe the code is very simple. I'm trying to learn my way through CoreData, but I can't seem to properly make it work.
It crashes here, when I press add to go to the 3rd view controller:
Can anyone help me? I'm new to this stuff! Thanks in advance