1

Im trying to pass a string from IDNumber in VCOne to postString in VCTwo. Ive tried a few different methods but no success. any help would be greatly appreciated! (Im also not using StoryBoards or SwiftUI) All code works, Apart from the passing between the two VC's

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.
    }
    */

}
General Grievance
  • 4,555
  • 31
  • 31
  • 45
  • 1
    Possible duplicate of: [Passing Data between View Controllers](https://stackoverflow.com/questions/5210535/passing-data-between-view-controllers) – TylerP Apr 21 '20 at 06:43

2 Answers2

0

define postString in class scope

var postString:String = ""

Assign the second VC postString from FirstVC before push

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

now you can use the postString in second VC

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()
    }
Dilan
  • 2,610
  • 7
  • 23
  • 33
  • I get this console Message "Error serializing json: dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.})))" – Lachy Schumacher Apr 21 '20 at 11:26
  • check the value before call API. if postString value is there that is the answer for your question. This error related to API call. – Dilan Apr 21 '20 at 11:29
0

you can do like this:

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()
}


}
Anil Kumar
  • 1,830
  • 15
  • 24
  • 1
    I get this console Message "Error serializing json: dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.})))" – Lachy Schumacher Apr 21 '20 at 11:25
  • this issue related to your api. it may come when you pass the wrong params , space in between the url cross check this and may be the header content type is different. – Anil Kumar Apr 21 '20 at 12:08