Как передать строку между контроллерами Diffirent View программно (Swift) - PullRequest
1 голос
/ 21 апреля 2020

Я пытаюсь передать строку от IDNumber в VCOne до postString в VCTwo. Я пробовал несколько разных методов, но безуспешно. любая помощь будет принята с благодарностью! (Я также не использую StoryBoards или SwiftUI). Весь код работает, кроме передачи между двумя V C *

ViewControllerOne:

import UIKit

class ViewControllerOne: UIViewController {

    var IDNumber : UITextView = {
        var PNTF = UITextView()
        PNTF.translatesAutoresizingMaskIntoConstraints = false
        PNTF.isUserInteractionEnabled = true
        PNTF.isEditable = true
        PNTF.layer.borderColor = CGColor.init(srgbRed: 0, green: 0, blue: 0, alpha: 1)
        PNTF.layer.borderWidth = CGFloat.init(1)
        PNTF.layer.cornerRadius = CGFloat.init(7.5)
        PNTF.layer.masksToBounds = true
        PNTF.font = UIFont(name: "HelveticaNeue", size: 20)
        PNTF.keyboardType = .asciiCapable
        PNTF.keyboardAppearance = .dark
        return PNTF
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(IDNumber)
        setupLayout()
        SetupNavBar()

        // Do any additional setup after loading the view.
    }
    func SetupNavBar() {
        navigationItem.title = "VC One"
        let titleFont = [NSAttributedString.Key.font : UIFont(name: "HelveticaNeue", size: 20)!]
        navigationController?.navigationBar.titleTextAttributes = titleFont
        navigationController?.navigationBar.barTintColor = .systemBackground
        navigationController?.navigationBar.prefersLargeTitles = false
        let SegueToVCTwo = UIBarButtonItem(image: UIImage(systemName: "checkmark.square"), style: .plain, target: self, action: #selector(Segue))
        self.navigationItem.leftBarButtonItem = SegueToVCTwo
    }
    @objc func Segue() {
        let segue = UINavigationController(rootViewController: ViewControllerTwo())
        segue.modalPresentationStyle = .pageSheet
        self.navigationController?.present(segue, animated: true)
    }
    func setupLayout() {

        IDNumber.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 15).isActive = true
        IDNumber.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor, constant: 15).isActive = true
        IDNumber.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor, constant: -15).isActive = true
        IDNumber.heightAnchor.constraint(equalToConstant: 15).isActive = true
    }
}

ViewControllerTwo:

import UIKit

class ViewControllerTwo: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        SetupNavBar()


        // Do any additional setup after loading the view.
    }
    func SetupNavBar() {
        navigationItem.title = "VC Two"
        let titleFont = [NSAttributedString.Key.font : UIFont(name: "HelveticaNeue", size: 20)!]
        navigationController?.navigationBar.titleTextAttributes = titleFont
        navigationController?.navigationBar.barTintColor = .systemBackground
        navigationController?.navigationBar.prefersLargeTitles = false
    }
    func QueryChipNumber() {
        let request = NSMutableURLRequest(url: NSURL(string: "https://api.tskfce.com/snapdragon.php")! as URL)
            request.httpMethod = "POST"
            let postString = "ID=\()"
            request.httpBody = postString.data(using: String.Encoding.utf8)
            let task = URLSession.shared.dataTask(with: request as URLRequest){data, response, error in
                guard error == nil && data != nil else{
                    print("error")
                    return
                }
                if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200{
                    print("statusCode should be 200, but is \(httpStatus.statusCode)")
                    print("response = \(String(describing: response))")
                }
            }
            task.resume()
    }


    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

Ответы [ 2 ]

0 голосов
/ 21 апреля 2020

вы можете сделать так:

class ViewControllerOne: UIViewController {

func jumpToVc2() {
        let vc = ViewControllerTwo()
        vc.postString = IDNumber.text ?? ""
        let segue = UINavigationController(rootViewController: vc)
        segue.modalPresentationStyle = .pageSheet
        self.navigationController?.present(segue, animated: true)
}
}

class ViewControllerOne: UIViewController {
var postString = String()
 //you can user poststring anywhere you want
func QueryChipNumber() {
    let request = NSMutableURLRequest(url: NSURL(string: "https://api.tskfce.com/snapdragon.php")! as URL)
        request.httpMethod = "POST"
        request.httpBody = "ID=\(postString)".data(using: String.Encoding.utf8)
        let task = URLSession.shared.dataTask(with: request as URLRequest){data, response, error in
            guard error == nil && data != nil else{
                print("error")
                return
            }
            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200{
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(String(describing: response))")
            }
        }
        task.resume()
}


}
0 голосов
/ 21 апреля 2020

определение postString в области видимости класса

var postString:String = ""

Назначение второй V C postString от FirstV C до pu sh

@objc func Segue() {
        let vc = ViewControllerTwo()
        vc.postString = IDNumber.text ?? ""
        let segue = UINavigationController(rootViewController: vc)
        segue.modalPresentationStyle = .pageSheet
        self.navigationController?.present(segue, animated: true)
    }

Теперь вы можете использовать postString в секунду V C

func QueryChipNumber() {
        let request = NSMutableURLRequest(url: NSURL(string: "https://api.tskfce.com/snapdragon.php")! as URL)
            request.httpMethod = "POST"

            request.httpBody = postString.data(using: String.Encoding.utf8)
            let task = URLSession.shared.dataTask(with: request as URLRequest){data, response, error in
                guard error == nil && data != nil else{
                    print("error")
                    return
                }
                if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200{
                    print("statusCode should be 200, but is \(httpStatus.statusCode)")
                    print("response = \(String(describing: response))")
                }
            }
            task.resume()
    }
...