load qr code link in UIwebview swift iOS - ios

hello everybody i have a webview VViewController.swift and
QRCode Scanner QRRViewController.swift how to load the QR Code if its url to a web view direct and not to safari ?
VVCiewcontroller.swift
import UIKit
class VViewController: UIViewController {
#IBOutlet weak var WWebView: UIWebView!
var QRLink:String!
override func viewDidLoad() {
super.viewDidLoad()
var url = NSURL(string: QRLink)
var request = NSURLRequest(URL: url!)
WWebView.loadRequest(request)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func goBack(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
QRRViewController.swift lok like this
this code load the Qr code URL to safari and not to web view
.......
if metadataObj.type == AVMetadataObjectTypeQRCode {
let barCodeObject = videoPreviewLayer?.transformedMetadataObjectForMetadataObject(metadataObj as AVMetadataMachineReadableCodeObject) as! AVMetadataMachineReadableCodeObject
qrCodeFrameView?.frame = barCodeObject.bounds;
if metadataObj.stringValue != nil {
messageLabel.text = metadataObj.stringValue
//if the result is url...
UIApplication.sharedApplication().openURL(NSURL(string: metadataObj.stringValue)!)
}
}

Assuming that you move from the QR view controller to the web views view controller, use the prepare for segue method to pass the link to the next view.
Add this to the QR view controller
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
// Create a variable that you want to send
var QRLink = self.QRLink
// Create a new variable to store the instance of PlayerTableViewController
let destinationVC = segue.destinationViewController as VViewController
destinationVC.QRLink = QRLink
}
Dont forget, you need to also add the variable in the webviews controller to store the QR link.
VVCiewcontroller.swift
import UIKit
class VViewController: UIViewController {
private var QRLink: String
#IBOutlet weak var WWebView: UIWebView!
var QRLink:String!
override func viewDidLoad() {
super.viewDidLoad()
var url = NSURL(string: QRLink)
var request = NSURLRequest(URL: url!)
WWebView.loadRequest(request)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func goBack(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
}

I assume that you are able to retrieve the string from your qr code reader function,
, also that you have a webview, so try this:
let request = NSURLRequest(URL: "THE URL FROM QRCode")
wvScreen.loadRequest(request)

Related

How to Handle Image uploading in WKWebview?

I have use webkit to show url on my app.
when I click on image button(green button in ), it shows
camera or photo library.
issue is, when click Use photo, the webkit
refresh automatically instead showing on page
I have already give photo usage, media, camera permission in plist file
my code is
import UIKit
import WebKit
import Alamofire
class ContinueViewController: UIViewController, WKUIDelegate {
#IBOutlet weak var activityView: UIActivityIndicatorView!
#IBOutlet weak var webview: WKWebView!
func getPostString(params:[String:Any]) -> String{
var data = [String]()
for(key, value) in params
{
data.append(key + "=\(value)")
}
return data.map { String($0) }.joined(separator: "&")
}
var url: URL?
var traderCategoryId = 0, tradeSkillId = 0
override func viewDidLoad() {
super.viewDidLoad()
webview.navigationDelegate = self
self.navigationController?.navigationBar.isHidden = false
webview.uiDelegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
activityView.startAnimating()
guard let url = self.url else { return }
var req = URLRequest(url: url)
let params = ["id" : id,"trader_skills" : tradeSkillId]
let postString = self.getPostString(params: params)
req.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
req.httpMethod = "POST"
req.httpBody = postString.data(using: .utf8)
self.webview.load(req)
}
}
extension ContinueViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
activityView.stopAnimating()
}
}
extension UIImagePickerController {
open override func viewDidLoad() {
super.viewDidLoad()
// self.modalPresentationStyle = .fullScreen
}
}
issue is, when click Use photo, the webkit refresh automatically instead showing on page
Because you self.webview.load(req) in
override func viewWillAppear(_ animated: Bool) {
shows camera or photo library, then return to this page
func viewWillAppear called again
self.webview.load(req) called again
do it simple ,
put self.webview.load(req) the relevant in
override func viewDidLoad() {

Add elements to search history?

I have a model - Movies.
and two controllers - first for search movie by title, second - for display result with poster, title and year.
Now i need to create some history search on my third controller
(searchHistoryController - TableView) where displayed all movies, and when i tapped on cell with movie's title show movie info.
How I can build it?
I tried create array in my model. And write resutl in it, but each time when i use search it rewrite array, not add new element.
Maybe use realm
Need some help:)
Movie.swift
import Foundation
import UIKit
import Alamofire
import AlamofireImage
protocol MovieDelegate {
func updateMovieInfo()
}
class Movie {
private let omdbUrl = "http://www.omdbapi.com/?"
var title: String?
var filmYear: String?
var poster: String?
var delegete: MovieDelegate!
var historyMovie = [Movie]()
func getMovieInfo(title: String, completion: #escaping ()->()){
let params = ["t": title]
Alamofire.request(omdbUrl, method: .get, parameters: params).validate(statusCode: 200..<300).validate(contentType: ["application/json"]).responseJSON { (response) in
switch response.result {
case .success(let JSON):
let response = JSON as! NSDictionary
let status = response["Response"] as! String
if status == "True" {
self.title = (response["Title"] as! String)
self.filmYear = (response["Year"] as! String)
self.poster = (response["Year"] as! String)
// self.delegete.updateMovieInfo()
completion()
} else {
self.title = (response["Error"] as! String)
completion()
}
case .failure(let error):
print (error)
}
}
}
}
SearchVC
import UIKit
class SearchViewController: UIViewController {
var movie = Movie()
#IBOutlet weak var activityIndicator: UIActivityIndicatorView!
#IBOutlet weak var searchTextField: UITextField!
#IBOutlet weak var searchButton: UIButton!
#IBAction func searchButtonTapped(_ sender: UIButton) {
activityIndicator.startAnimating()
DispatchQueue.main.async {
self.movie.getMovieInfo(title: self.searchTextField.text!, completion: {
self.activityIndicator.stopAnimating()
self.performSegue(withIdentifier: "movieInfo", sender: self)
})
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let secondVC = segue.destination as! DetailInfoViewController
secondVC.movieTitle = movie.title!
}
}
DetailVC
class DetailInfoViewController: UIViewController, MovieDelegate {
#IBAction func showHistory(_ sender: UIButton) {
performSegue(withIdentifier: "showHistory", sender: self)
}
#IBOutlet weak var posterImageView: UIImageView!
#IBOutlet weak var filmNameLabel: UILabel!
#IBOutlet weak var filmYearLabel: UILabel!
var movie = Movie()
var movieTitle = ""
override func viewDidLoad() {
super.viewDidLoad()
self.movie.getMovieInfo(title: movieTitle ) {
self.updateMovieInfo()
}
self.movie.delegete = self
}
func updateMovieInfo() {
getPoster(link: movie.poster)
filmNameLabel.text = movie.title
filmYearLabel.text = movie.filmYear
}
func getPoster(link: String?) {
if link != nil {
guard let url = URL(string: link!) else { return }
DispatchQueue.global().async {
if let data = try? Data(contentsOf: url) {
DispatchQueue.main.async {
self.posterImageView.image = UIImage(data: data)
}
}
} } else {
self.posterImageView.image = #imageLiteral(resourceName: "Image")
}
}
}
First of all, movieHistory should not be part of your Movie class, but part of your SearchViewController class.
Second of all, unless you want to persist your data, you don't need Realm for this.
Just save the movies in SearchViewController into an array once the search button has been tapped and send it to your other view controller in the segue. Like so
#IBAction func searchButtonTapped(_ sender: UIButton) {
activityIndicator.startAnimating()
DispatchQueue.main.async {
self.movie.getMovieInfo(title: self.searchTextField.text!, completion: {
self.activityIndicator.stopAnimating()
movieHistory.append(movie)
self.performSegue(withIdentifier: "movieInfo", sender: movieHistory)
})
}
}
Also, modify prepare(for segue:...) like this:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let secondVC = segue.destination as! DetailInfoViewController
secondVC.movieTitle = movie.title!
secondVC.movieHistory = movieHistory
}
In detailVC override prepare(for segue:...) as well and send movieHistory to searchHistoryController the same way it is done in the previous VC.

iOS Swift : can't Retrieve current url loaded in UIwebView

i am working in webview application iOS swift :
problem i am facing is i want to get each url which webview displays :
upon urls i have to perform some if else checks . but i could not get the urls which webview loads.
webview is displaying fine results and loading urls upon clicking . i want to fetch all urls which webview navigates on..
import Foundation
import UIKit
class seconVC: UIViewController {
var toPass:String!
var touser:String!
var toPassing:String!
#IBOutlet weak var webV: UIWebView!
#IBOutlet weak var L_back: UIBarButtonItem!
#IBOutlet weak var R_frwrd: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var domurl = toPass;
var username = touser;
var passwing = toPassing;
var sendurl = stringA+username+"/"+passwing;
//exchange login with auth/username/password
println(sendurl);
let url = NSURL (string: sendurl);
let requestObj = NSURLRequest(URL: url!);
webV.userInteractionEnabled = true
webV.loadRequest(requestObj);
}
#IBAction func L_back(sender: UIBarButtonItem) {
if (webV.canGoBack){
webV.goBack()
}
}
#IBAction func R_frwrd(sender: UIBarButtonItem) {
if (webV.canGoForward){
webV.goForward()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
all i want is to get string of current url and navigation buttons for webview :please help ? i referred all the internet no solution is working in my case .
There are couple of UIWebViewDelegate such as shouldStartLoadWithRequest or webViewDidStartLoad or webViewDidFinishLoad or didFailLoadWithError that help you to accomplish your goal. If you want to perform operation after view did finished then implement this delegate method
Swift 3
if let currentURL = webView.request?.url?.absoluteString{
print(currentURL)
}
as it mentioned here.
option-1
let currentURL = webV.request.URL.absoluteString
option-2
get URL in delegate method
func webViewDidFinishLoad(webView: UIWebView){
print(WebView.request?.mainDocumentURL)
}
option-3
func webViewDidFinishLoad(webView: UIWebView) {
let currentURL = webView.request().URL()
print("\(currentURL.description)")
}
or use like
func webViewDidFinishLoad(webView: UIWebView){
let currentURL = webView.request?.URL
}
option-4
func webViewDidFinishLoad(webView: UIWebView) {
let currentURL: = webView.stringByEvaluatingJavaScriptFromString("window.location.href")!
print("\(currentURL)")
}
option-5
func webView(webview: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
let currentURL = request.URL.absoluteString
print("\(currentURL)")
}
option-6
func webViewDidFinishLoad(WebVie: UIWebView) {
let currentURL = WebVie.request.mainDocumentURL
print("\(currentURL)")
}
First you have to define the delegate for WebView class. "WebView.delegate = self". Add this code beside one of the function above:
override func viewDidLoad() {
super.viewDidLoad()
myWebView.delegate = self }
and for exmaple:
func webViewDidFinishLoad(_ webView: UIWebView) {
if let currentURL = WebView.request?.url?.absoluteString{
print(currentURL)
}
}

Make UIButton Click Display UIWebview

I'm trying to load a specific URL after clicking a button. I have the webView code inside of a UIButton action, but I'm not sure how to pull that into the display/viewDidLoad method it will work. But I need to be able to change the URL with different buttons.
import UIKit
class ViewController: UIViewController {
var radioURL = "http://www.ladiescanwetalk.org/category/podcasts/"
#IBOutlet weak var mainWebView: UIWebView!
#IBAction func loadRadioView(sender: UIButton) {
let getCurrentURL = NSURL (string: radioURL)
let requestCurrentURL = NSURLRequest(URL: getCurrentURL!)
self.mainWebView?.loadRequest(requestCurrentURL)
}
override func viewDidLoad() {
super.viewDidLoad()
}
In my opinion the best to achieve what you're asking is to set a different tag value for each value (you can do this either using Storyboard or directly via code).
Your code will be something like this:
#IBAction func loadRadioView(sender: UIButton) {
if sender.tag == 1 {
radioURL = "http://anotherUrl"
} else if sender.tag == 2 {
radioURL = "http://yetanotherurl"
} else if sender.tag == 3 {
radioURL = "http://....."
}
let getCurrentURL = NSURL (string: radioURL)
let requestCurrentURL = NSURLRequest(URL: getCurrentURL!)
self.mainWebView?.loadRequest(requestCurrentURL)
}

Value of type 'PlaySoundsViewController' has no member 'recordedAudio'

I've been following Udacity's Intro to iOS App Development with Swift tutorial, but got this error.
Value of type 'PlaySoundsViewController' has no member 'recordedAudio'
Line 84 has the error.
playSoundsVC.recordedAudio = recordedAudioURL
Here is the entire code:
import UIKit
import AVFoundation
class RecordSoundsViewController: UIViewController , AVAudioRecorderDelegate {
#IBOutlet weak var recordingInProgress: UILabel!
#IBOutlet weak var stopButton: UIButton!
#IBOutlet weak var recordButton: UIButton!
var audioRecorder:AVAudioRecorder!
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 viewWillAppear(animated: Bool) {
//TODO: Hide stop button
stopButton.hidden = true
//TODO: Enable recordButton
recordButton.enabled = true
}
#IBAction func recordAudio(sender: AnyObject) {
//TODO: Show text "recording in progress"
recordingInProgress.hidden = false
//TODO: Show stopButton
stopButton.hidden = false
//TODO: Record the user's voice
print("in recordAudio")
//TODO: Disable recording button
recordButton.enabled = false
let dirPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask, true)[0] as String
let recordingName = "recordedVoice.wav"
let pathArray = [dirPath, recordingName]
let filePath = NSURL.fileURLWithPathComponents(pathArray)
print(filePath)
let session = AVAudioSession.sharedInstance()
try! session.setCategory(AVAudioSessionCategoryPlayAndRecord)
try! audioRecorder = AVAudioRecorder(URL: filePath!, settings: [:])
audioRecorder.meteringEnabled = true
audioRecorder.prepareToRecord()
audioRecorder.record()
}
#IBAction func stopRecording(sender: AnyObject) {
//TODO: hide recordingInProgress label
recordingInProgress.hidden = true
recordButton.enabled = true
let audioSession = AVAudioSession.sharedInstance()
try! audioSession.setActive(false)
}
func audioRecorderDidFinishRecording(recorder: AVAudioRecorder, successfully flag: Bool) {
print("AVAudioRecorder finished saving recording")
if (flag) {
self.performSegueWithIdentifier("stopRecording", sender: audioRecorder.url)
} else {
print("Saving of recording failed")
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "stopRecording") {
let playSoundsVC = segue.destinationViewController as!
PlaySoundsViewController
let recordedAudioURL = sender as! NSURL
playSoundsVC.recordedAudio = recordedAudioURL
}
}
}
class PlaySoundsViewController: UIViewController {
var recordedURL: URL?
override func viewDidLoad() {
super.viewDidLoad()
}
}
Don't forget to add an identifier for segue:
add var recordedAudioURL:URL! to your PlaySoundsViewController file
it is a variable that holds the url in the next class which is been send from the current class.
happy coding :)
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "stopRecording") {
let playSoundsVC = segue.destinationViewController as! PlaySoundViewController
let recordedAudioURL = sender as! NSURL
playSoundsVC.recordedAudioURL = recordedAudioURL
}
}

Resources