Я создал одну раскадровку с именем Main1.storyboard, и эта раскадровка имеет внутренний файл с именем ViewController.swift.Все проекты созданы с помощью Swift 3.0.Эта раскадровка предназначена для чтения штрих-кода, которую я хочу сделать после чтения штрих-кода, чтобы открыть файл homeViewController.xib - homeViewController.swift и отправить этот результат штрих-кода.Класс HomeViewController имеет компоненты Webview.Для меня важно просто открыть homeViewController.xib - homeViewController.swift файл после считывания штрих-кода и отправить результат штрих-кода.Мой класс homeViewController.swift и ViewController.swift имеет следующий вид:
homeViewController.swift:
import UIKit
import SystemConfiguration
import DrawerController
import SVProgressHUD
class homeViewController: UIViewController , UIWebViewDelegate,UIScrollViewDelegate {
var webView: UIWebView!
var text:String = "http://www.google.com"
var barcode:String = ""
override func viewDidLoad() {
super.viewDidLoad()
// setup title
self.title = "My App"
// setup NavigationBar Color
self.navigationController?.navigationBar.barTintColor = navigationBarColor
let ud: UserDefaults = UserDefaults.standard
let data: NSData? = ud.object(forKey: "cookie") as? NSData
if let cookie = data {
let datas: NSArray? = NSKeyedUnarchiver.unarchiveObject(with: cookie as Data) as? NSArray
if let cookies = datas {
for c in cookies as! [HTTPCookie] {
HTTPCookieStorage.shared.setCookie(c)
}
}
}
// setup side Bar
if(sideBarPosition == "left"){
self.setupLeftMenuButton()
}
else{
self.setupRightMenuButton()
}
// setup WebView
webView = UIWebView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height-64))
self.view.addSubview(webView)
webView.delegate = self
webView.scrollView.delegate = self
webView.isUserInteractionEnabled = false
SVProgressHUD.show()
if (typeOfData == "html"){
// load from html file
let myfile = Bundle.main.url(forResource: nameFileHtml, withExtension: "html")
let requestObj = NSURLRequest(url: myfile!)
webView.loadRequest(requestObj as URLRequest)
}
else{
// load website data
if(connectedToNetwork() == false){
SVProgressHUD.showError(withStatus: "No Internet Connection")
}
else{
webView.loadRequest(URLRequest(url: URL(string: text)!))
}
}
}
// setup left menu button icon
func setupLeftMenuButton() {
let button = UIButton.init(type: .custom)
button.setImage(UIImage.init(named: "menuleft.png")?.withRenderingMode(.alwaysTemplate), for: UIControlState.normal)
button.addTarget(self, action:#selector(leftDrawerButtonPress), for: UIControlEvents.touchUpInside)
button.frame = CGRect.init(x: 0, y: 0, width: 30, height: 17) //CGRectMake(0, 0, 30, 30)
button.imageView?.tintColor = iconColor
let barButton = UIBarButtonItem.init(customView: button)
self.navigationItem.leftBarButtonItem = barButton
}
// setup left menu button action
func leftDrawerButtonPress(_ sender: AnyObject?) {
self.evo_drawerController?.toggleDrawerSide(.left, animated: true, completion: nil)
}
// setup right menu button icon
func setupRightMenuButton() {
let button = UIButton.init(type: .custom)
button.setImage(UIImage.init(named: "menuright.png")?.withRenderingMode(.alwaysTemplate), for: UIControlState.normal)
button.addTarget(self, action:#selector(rightDrawerButtonPress), for: UIControlEvents.touchUpInside)
button.frame = CGRect.init(x: 0, y: 0, width: 30, height: 17) //CGRectMake(0, 0, 30, 30)
button.imageView?.tintColor = iconColor
let barButton = UIBarButtonItem.init(customView: button)
self.navigationItem.rightBarButtonItem = barButton
}
// setup right menu button action
func rightDrawerButtonPress(_ sender: AnyObject?) {
self.evo_drawerController?.toggleDrawerSide(.right, animated: true, completion: nil)
}
// setup webView option
func webViewDidStartLoad(_ webView: UIWebView)
{
SVProgressHUD.show()
}
func webViewDidFinishLoad(_ webView: UIWebView)
{
if( barcode != "")
{
self.webView.stringByEvaluatingJavaScript(from:
"var element = document.getElementById('input-password');"
+ "element.value ="+barcode+";" +
"")
}
let cookieJar: HTTPCookieStorage = HTTPCookieStorage.shared
let data: NSData = NSKeyedArchiver.archivedData(withRootObject: cookieJar.cookies) as NSData
let ud: UserDefaults = UserDefaults.standard
ud.set(data, forKey: "cookie")
SVProgressHUD.dismiss()
webView.isUserInteractionEnabled = true
let aLabel = UIButton()
self.view.addSubview(aLabel)
aLabel.widthAnchor.constraint(equalToConstant: 100.0).isActive = true
aLabel.heightAnchor.constraint(equalToConstant: 123.0).isActive = true
aLabel.setImage(UIImage(named: "photo-camera.png"), for: .normal)
aLabel.translatesAutoresizingMaskIntoConstraints = false
let horizontalConstraint = NSLayoutConstraint(item: aLabel, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal, toItem: view, attribute:NSLayoutAttribute.trailing, multiplier: 1, constant: 0)
let verticalConstraint = NSLayoutConstraint(item: aLabel, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: 0)
aLabel.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
NSLayoutConstraint.activate([horizontalConstraint, verticalConstraint])
self.view.layoutIfNeeded()
}
@objc func buttonAction(sender: UIButton!) {
let storyBoard: UIStoryboard = UIStoryboard(name: "Main1", bundle: nil)
let balanceViewController = storyBoard.instantiateViewController(withIdentifier: "barcode") as! ViewController
self.present(balanceViewController, animated: true, completion: nil)
}
func btnclicked(sender: UIButton!)
{
let alert = UIAlertController(title: "Alert", message: "unwraped.stringValue", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
if (scrollView.contentOffset.y < 0){
self.webView.reload()
}
}
// check connection
func connectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
zeroAddress.sin_family = sa_family_t(AF_INET)
guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
SCNetworkReachabilityCreateWithAddress(nil, $0)
}
}) else {
return false
}
var flags: SCNetworkReachabilityFlags = []
if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
return false
}
let isReachable = flags.contains(.reachable)
let needsConnection = flags.contains(.connectionRequired)
return (isReachable && !needsConnection)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
ViewController.swift
import UIKit
import AVFoundation
class ViewController: UIViewController,UIScrollViewDelegate , UIWebViewDelegate , AVCaptureMetadataOutputObjectsDelegate {
@IBOutlet weak var viewPreview: UIView!
var captureSession: AVCaptureSession?
var videoPreviewLayer: AVCaptureVideoPreviewLayer!
var isReading: Bool = false
var barcoderesult:String=""
@IBOutlet weak var anulo_btn: UIButton!
@IBAction func bnt_cancel(_ sender: Any) {
let vc = homeViewController(nibName: "homeViewController", bundle: nil)
let navigationController = UINavigationController(rootViewController: vc)
self.evo_drawerController?.setCenter(navigationController, withCloseAnimation: true, completion: nil)
self.dismiss(animated: true)
}
// setup left menu button icon
func setupLeftMenuButton() {
let button = UIButton.init(type: .custom)
button.setImage(UIImage.init(named: "menuleft.png")?.withRenderingMode(.alwaysTemplate), for: UIControlState.normal)
button.addTarget(self, action:#selector(leftDrawerButtonPress), for: UIControlEvents.touchUpInside)
button.frame = CGRect.init(x: 0, y: 0, width: 30, height: 17) //CGRectMake(0, 0, 30, 30)
button.imageView?.tintColor = iconColor
let barButton = UIBarButtonItem.init(customView: button)
self.navigationItem.leftBarButtonItem = barButton
}
// setup left menu button action
func leftDrawerButtonPress(_ sender: AnyObject?) {
self.evo_drawerController?.toggleDrawerSide(.left, animated: true, completion: nil)
}
// MARK: - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.barTintColor = navigationBarColor
// setup title
setupLeftMenuButton()
viewPreview.layer.cornerRadius = 5;
captureSession = nil;
if !isReading {
if (self.startReading()) {
}
}
else {
stopReading()
}
isReading = !isReading
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - IBAction Method
@IBAction func startStopClick(_ sender: UIButton) {
if !isReading {
if (self.startReading()) {
}
}
else {
stopReading()
}
isReading = !isReading
}
// MARK: - Custom Method
func startReading() -> Bool {
let captureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
do {
let input = try AVCaptureDeviceInput(device: captureDevice)
captureSession = AVCaptureSession()
captureSession?.addInput(input)
// Do the rest of your work...
} catch let error as NSError {
// Handle any errors
print(error)
return false
}
videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
videoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
videoPreviewLayer.frame = viewPreview.layer.bounds
viewPreview.layer.addSublayer(videoPreviewLayer)
/* Check for metadata */
let captureMetadataOutput = AVCaptureMetadataOutput()
captureSession?.addOutput(captureMetadataOutput)
captureMetadataOutput.metadataObjectTypes = captureMetadataOutput.availableMetadataObjectTypes
print(captureMetadataOutput.availableMetadataObjectTypes)
captureMetadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
captureSession?.startRunning()
return true
}
func stopReading() {
captureSession?.stopRunning()
captureSession = nil
videoPreviewLayer.removeFromSuperlayer()
}
func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {
for data in metadataObjects {
let metaData = data as! AVMetadataObject
print(metaData.description)
let transformed = videoPreviewLayer?.transformedMetadataObject(for: metaData) as? AVMetadataMachineReadableCodeObject
if let unwraped = transformed {
print(unwraped.stringValue)
// lblString.text = unwraped.stringValue
// btnStartStop.setTitle("Start", for: .normal)
barcoderesult = unwraped.stringValue
let alert = UIAlertController(title: "Alert", message: unwraped.stringValue, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
self.performSelector(onMainThread: #selector(stopReading), with: nil, waitUntilDone: false)
isReading = false;
}
}
}
}