Unable to load WKWebView into containerView - wkwebview

I am trying to load a web view inside a container view which is basically a UIView inside the main View.But somehow its not loading.
var urlString : String!
var termsAndConditionsWebView : WKWebView!
#IBOutlet var containerView: UIView!
override func loadView() {
super.loadView()
//self.termsAndConditionsWebView.frame = containerView.frame
//self.termsAndConditionsWebView.sizeToFit()
self.termsAndConditionsWebView = WKWebView()
containerView = termsAndConditionsWebView
}
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL(string: "https://www.google.com.sg")
let request = NSURLRequest(URL: url!)
termsAndConditionsWebView.loadRequest(request)
}

Related

Value of type 'UIViewController' has no member 'mapView'; did you mean 'loadView'?

I try to Search for locations using MKLocalSearchRequest in Swift4 (for ios 12). When I append thelocationSearchTable.mapView = mapViewat the end of viewDidLoad I get the error.
In ViewController
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
#IBOutlet weak var mapView: MKMapView!
let locationManager = CLLocationManager()
var resultSearchController: UISearchController? = nil
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
let locationSearchTable = storyboard!.instantiateViewController(withIdentifier: "LocationSearchTable")
resultSearchController = UISearchController(searchResultsController: locationSearchTable)
resultSearchController?.searchResultsUpdater = locationSearchTable as! UISearchResultsUpdating
let searchBar = resultSearchController!.searchBar
searchBar.sizeToFit()
searchBar.placeholder = "Search for places"
navigationItem.titleView = resultSearchController?.searchBar
resultSearchController?.hidesNavigationBarDuringPresentation = false
resultSearchController?.dimsBackgroundDuringPresentation = true
definesPresentationContext = true
locationSearchTable.mapView = mapView
}...
In the LocationSearchTable
import UIKit
import MapKit
class LocationSearchTable: UITableViewController {
var matchingItems: [MKMapItem] = []
var mapView: MKMapView? = nil
}
extension LocationSearchTable: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
guard let mapView = mapView,
let searchBarText = searchController.searchBar.text else { return }
let request = MKLocalSearch.Request()
request.naturalLanguageQuery = searchBarText
request.region = mapView.region
let search = MKLocalSearch(request: request)
search.start { response, _ in
guard let response = response else {
return
}
self.matchingItems = response.mapItems
self.tableView.reloadData()
}
}
}...
Maybe locationSearchTable is not LocationSearchTable class.
Try the following code
if let locationSearchTable = locationSearchTable as? LocationSearchTable {
locationSearchTable.mapView = mapView
}

Issues with UserDefaults.standard.value(forKey: "barcodeId") as! String

Can anyone tell me why the copied data from user defaults is not passing the correct value? Below is my code, the weird part about all of this is outside of the app, when pasting on to notes or safari on the device. It does indeed past the correct data. NOTE: I've removed the test url
let testURL = ""
// let barcodeData = UserDefaults.standard.value(forKey: "barcodeId") as! String
var barcodeData = UserDefaults.standard.value(forKey: "barcodeId") as! String
override func viewDidLoad() {
super.viewDidLoad()
}
#IBOutlet weak var webView: WKWebView!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
webView.navigationDelegate = self
load(urlString: testURL)
}
// MARK: Private function
func load(urlString string: String) {
let url = URL(string: string)
let request = URLRequest(url: url!)
webView.load(request)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
webView.evaluateJavaScript("document.getElementById('RCPT_BARCODE').value = \(barcodeData)") {(result, error) in
guard error == nil else {
print(error!)
return
}
print(String(describing: result))
}
}
}

Black window when navigating from App delegate in xamarin Ios

I'm getting a black window after navigating to a view controller. My app is calling a page from app delegate from the OpenUrl method.
public override bool OpenUrl(UIApplication app, NSUrl url, string sourceApp, NSObject annotation)
{
var rurl = new Rivets.AppLinkUrl(url.ToString());
// navController = new UINavigationController();
var id = string.Empty;
if (rurl.InputQueryParameters.ContainsKey("id"))
id = rurl.InputQueryParameters["id"];
if (rurl.InputUrl.Host.Equals("products") && !string.IsNullOrEmpty(id))
{
// var mainController = new UIViewController();
// NSUserDefaults.StandardUserDefaults.SetBool(true, "ForgotPwdLinkClicked");
return true;
}
else
{
//var c = new ProductViewController();
// UIApplication.SharedApplication.KeyWindow.RootViewController = c;
var c = new UpdatePasswordViewController();
navigationController.ModalPresentationStyle = UIModalPresentationStyle.OverFullScreen;
navigationController.PushViewController
(c, true);
//// return true ;
///*this.Window.RootViewController =
// c;*/
// NSUserDefaults.StandardUserDefaults.SetBool(true, "ForgotPwdLinkClicked");
return true;
}
}
These are my ViewController settings in XCode:
This Code resolve my issue
UIStoryboard Storyboard = UIStoryboard.FromName("MainStoryboard", null);// this will bee our storyboard name
var c = Storyboard.InstantiateViewController("UpdatePasswordViewController") as UpdatePasswordViewController;

How to write into the CoreData entity at the same index in different view controller (also swift files)

I have created core data using 'NSFetchedResultController' and 'managedObjectContext' in a table view. But in the later view controller, after gathering accelerometer data and conduct calculation, I will get some results that I also want to store in the same row index with the core data I created before.
How can I achieve this? If I create managedObjectContext again, it will create another 'row' of core data in this table.
The code in tableViewController:
'
let managedObjectContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext
var fetchedResultController: NSFetchedResultsController = NSFetchedResultsController()
override func viewDidLoad() {
super.viewDidLoad()
fetchedResultController = getFetchedResultController()
fetchedResultController.delegate = self
fetchedResultController.performFetch(nil)
}
func getFetchedResultController() -> NSFetchedResultsController {
fetchedResultController = NSFetchedResultsController(fetchRequest: trialFetchRequest(), managedObjectContext: managedObjectContext!, sectionNameKeyPath: nil, cacheName: nil)
return fetchedResultController
}
func trialFetchRequest() -> NSFetchRequest {
let fetchRequest = NSFetchRequest(entityName: "Trials")
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "date", ascending: true)]
return fetchRequest
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
let numberOfSections = fetchedResultController.sections?.count
return numberOfSections!
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let numberOfRowsInSection = fetchedResultController.sections?[section].numberOfObjects
return numberOfRowsInSection!
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
let trial = fetchedResultController.objectAtIndexPath(indexPath) as Trials
cell.textLabel?.text = trial.trialName
cell.detailTextLabel?.text = trial.date?.description
return cell
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
let managedObject:NSManagedObject = fetchedResultController.objectAtIndexPath(indexPath) as NSManagedObject
managedObjectContext?.deleteObject(managedObject)
managedObjectContext?.save(nil)
}
func controllerDidChangeContent(controller: NSFetchedResultsController!) {
tableView.reloadData()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if segue.identifier == "showTrial" {
let indexPath = tableView.indexPathForSelectedRow()
let trial:Trials = fetchedResultController.objectAtIndexPath(indexPath!) as Trials
let trialController:TrialDetailViewController = segue.destinationViewController as TrialDetailViewController
trialController.trial = trial
}
}
'
The code in the createTrial Controller:
' let managedObjectContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if segue.identifier == "createTrial" {
if theTrialName.text != "" {
createTrial()
} else {
let alertView = UIAlertController(title: "", message: "Trial name couldn't be empty", preferredStyle: .Alert)
alertView.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))
presentViewController(alertView, animated: true, completion: nil)
}
}
}
func createTrial() {
let entityDescripition = NSEntityDescription.entityForName("Trials", inManagedObjectContext: managedObjectContext!)
let trial = Trials(entity: entityDescripition!, insertIntoManagedObjectContext: managedObjectContext)
trial.trialName = theTrialName.text
trial.location = theLocation.text
trial.notes = theNotes.text
if theArm.on {
trial.arm = 1
} else {
trial.arm = 0
}
managedObjectContext?.save(nil)
}
'
ps. the view controller I want to get data from is not this following segue, it is around 3 view afterwards. And I have created a string to store the data I need in that view.
I solved the problem by creating the object in the tableViewControllerand use segue twice to transmit it to secondViewControllerand thirdViewController. So it will be at the same index for the whole time. And I can change the content of the core data at both the following view controllers.

SWIFT: Why is "NSURL(string:" returning with Nil, even though it's a valid url in a browser?

The first two example links are working the third one returns NIL.
Why is NSUrl returning nil for such string, even though it's a valid url in a browser?
Am I supposed to process the string more?
Here is my code:
import UIKit
import Foundation
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, NSXMLParserDelegate {
var myFeed : NSArray = []
var url : NSURL!
var feedURL : NSURL!
var selectedFeedURL = String()
#IBOutlet var tableFeeds: UITableView!
#IBOutlet var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Set feed url.
//url = NSURL(string: "http://www.skysports.com/rss/0,20514,11661,00.xml")! //This seems to work
//url = NSURL(string: "http://www.formula1.com/rss/news/latest.rss")! //This seems to work
url = NSURL(string: "http://www.multirotorusa.com/feed/")!
loadRss(url);
}
func loadRss(data: NSURL) {
var myParser : XmlParserManager = XmlParserManager.alloc().initWithURL(data) as XmlParserManager
myFeed = myParser.feeds
tableFeeds.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myFeed.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
var dict : NSDictionary! = myFeed.objectAtIndex(indexPath.row) as NSDictionary
cell.textLabel?.text = myFeed.objectAtIndex(indexPath.row).objectForKey("title") as? String
cell.detailTextLabel?.text = myFeed.objectAtIndex(indexPath.row).objectForKey("description") as? String
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var indexPath: NSIndexPath = self.tableFeeds.indexPathForSelectedRow()!
var selectedFeedURL = myFeed.objectAtIndex(indexPath.row).objectForKey("link") as String
selectedFeedURL = selectedFeedURL.stringByReplacingOccurrencesOfString(" ", withString:"")
selectedFeedURL = selectedFeedURL.stringByReplacingOccurrencesOfString("\n", withString:"")
// feedURL = NSURL(fileURLWithPath: selectedFeedURL) //This returns with: URL + /%09%09 -- file:///
feedURL = NSURL(string: selectedFeedURL) //This returns with NIL
println("Selected Feed URL: \(selectedFeedURL)")
println("Feed URL: \(feedURL)")
if feedURL != nil {
let request : NSURLRequest = NSURLRequest(URL: feedURL!)
webView.loadRequest(request)
println("Feed URL: \(feedURL)") //Doesn't make it here
}
}
}
Any suggestions?
You should URL-encode the URL like this:
selectedFeedUrl = selectedFeedUrl.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
In iOs 9:
myString = myString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
Hope it helps
For swift3 you can do like this
let url = URL(string:url.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)!)!
Thank you guys for your help.
I added these two lines to my code and it works now:
selectedFeedURL = selectedFeedURL.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
selectedFeedURL = selectedFeedURL.stringByReplacingOccurrencesOfString("%09%09", withString:"")

Resources