点击OK按钮时如何在屏幕中央显示活动指示?我正在使用AVCaptureVideoPreviewLayer对象并显示相机,当我们扫描QR码时会出现警告框,按下OK按钮后它会调用API,此时我想出现UIActivityIndicator。
import UIKit
import AVFoundation
class QRCodeScanner: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
@IBOutlet weak var imgClose: UIImageView!
var video = AVCaptureVideoPreviewLayer()
var strQR = String()
override func viewDidLoad() {
super.viewDidLoad()
//Creating session
let session = AVCaptureSession()
//Capture device
//var captureDevice = AVCaptureDevice.default(for: AVMediaType.video)
let captureDevice = AVCaptureDevice.default(AVCaptureDevice.DeviceType.builtInWideAngleCamera, for: AVMediaType.video, position: .front)
do {
let input = try AVCaptureDeviceInput(device: captureDevice!)
session.addInput(input)
}
catch {
print("Error")
}
let output = AVCaptureMetadataOutput()
session.addOutput(output)
output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
output.metadataObjectTypes = [AVMetadataObject.ObjectType.qr]
video = AVCaptureVideoPreviewLayer(session: session)
video.frame = view.layer.bounds
view.layer.addSublayer(video)
//Show Image in Camera Mode
let myLayer = CALayer()
let myImage = UIImage(named: "icn-close")?.cgImage
myLayer.frame = CGRect(x: self.view.frame.size.width - CGFloat((myImage?.width)!) - 10, y: 16, width: 32, height: 35)
myLayer.contents = myImage
video.addSublayer(myLayer)
self.view.bringSubview(toFront: self.view)
session.startRunning()
}
@IBAction func btnClose(_ sender: Any)
{
self.navigationController?.popViewController(animated: true)
}
func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection)
{
if metadataObjects.count == 0 {
//qrCodeFrameView?.frame = CGRect.zero
//messageLabel.text = "No QR code is detected"
return
}
// Get the metadata object.
let object = metadataObjects[0] as? AVMetadataMachineReadableCodeObject
let supportedCodeTypes = AVMetadataObject.ObjectType.qr
if supportedCodeTypes == .qr {
// If the found metadata is equal to the QR code metadata (or barcode) then update the status label's text and set the bounds
//let barCodeObject = videoPwreviewLayer?.transformedMetadataObject(for: metadataObj)
//qrCodeFrameView?.frame = barCodeObject!.bounds
let alert = UIAlertController(title: "QR Code", message: object?.stringValue, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Retake", style: .default, handler: nil))
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (nil) in
self.strQR = (object?.stringValue)!
//print("strQR")
activityIndicator.startAnimating()
self.api(strURL: urlQRCode)
}))
present(alert, animated: true, completion: nil)
if object?.stringValue != nil {
//launchApp(decodedURL: metadataObj.stringValue!)
//messageLabel.text = metadataObj.stringValue
}
}
}
func api(strURL: String)
{
//URL
let myURL = URL(string: strURL)
//URL Request
let request = NSMutableURLRequest(url: myURL!)
request.httpMethod = "POST"
//Passing the strOTP text in the dictionary variable
let postString = ["qr_code": strQR]
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let token = "Bearer " + strToken
request.addValue(token, forHTTPHeaderField: "Authorization")
do {
// pass dictionary to nsdata object and set it as request body
request.httpBody = try JSONSerialization.data(withJSONObject: postString, options: .prettyPrinted)
//print("Successfully passed data to server")
} catch let error {
print(error.localizedDescription)
}
let postTask = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in
//print(response!)
guard error == nil else {
return
}
guard let data = data else {
return
}
do {
//create json object from data
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
print("POST Method :\(json)")
let dict = json as? [String: String]
let status = dict!["status"]
print("Status : \(String(describing: status))")
//Match the status code (received from response through the server
if dict!["status"] == "1"
{
DispatchQueue.main.async {
//Stop Activity Indicator
activityIndicator.stopAnimating()
print("The status received from server is 1. Entered Successfully to OTP Screen")
let thankVC = self.storyboard?.instantiateViewController(withIdentifier: "ThankYouVC") as! ThankYouVC
thankVC.strEmpName = dict!["whom_to_meet"]!
self.navigationController?.pushViewController(thankVC, animated: true)
}
}
else
{
print("The status received from server is 0.")
let whoopsPopupVC = self.storyboard?.instantiateViewController(withIdentifier: "Popup_Whoops") as! Popup_Whoops
whoopsPopupVC.strDetail = "You are not a registered user."
self.navigationController?.present(whoopsPopupVC, animated: true, completion: nil)
}
// handle json...
}
} catch let error {
print(error.localizedDescription)
}
}
postTask.resume()
}
}