I am just trying to create a simple webview inside a view controller.
Here is my code:
import UIKit
class test:UIViewController{
#IBOutlet weak var myWebView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var myString = "http://www.google.com"
let myURL = NSURL(string: myString)
let myReq = NSURLRequest(URL: myURL)
myWebView.loadRequest(myReq)
println(myWebView.loading)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I'm not getting any errors, simply a white screen. The loading check returns false. It seems like it should be the outlet connection, but I am sure I've made the proper connection. I ctrl-dragged the blue UIWebView element from storyboard into the class as the UIWebView! object and named it myWebView. The circle is filled in on the swift file indicating a connection, and they match up in the connections on the storyboard.
This code originally worked fine for me, but now it does not. I tried creating a completely new project and it still is not working. Adding the UIWebViewDelegate protocol to the class didn't work I've looked at the solutions on the following links, but they do not apply:
link1
link2
I'm out of ideas. Anyone got anything?
Thanks!
This is what you wan in viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var myWeb = UIWebView(frame: CGRect(x: 40, y: 100, width: 240, height: 128))
var myString = "http://www.google.com"
let myURL = NSURL(string: myString)
let myReq = NSURLRequest(URL: myURL!)
myWeb.loadRequest(myReq)
view.addSubview(myWeb)
println(myWeb.loading)
}
Be careful, you have another web view (called myWebView) from the storyboard, as an outlet and that is not used. By writing the above code you create a new web view programmatically (called myWeb).
Related
I am new to xcode and Swift and I am getting an error
EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
I've tried searching similar questions on stackoverflow and I saw that people's responses were that it's because the url is not valid, so it's returning nil. However, I am using https://google.com and I am still getting the same error. This is all my code so far. I am only trying to load a single webpage into the view controller.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var myWebView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let url = URL(string: "https://www.google.com")
myWebView.loadRequest(URLRequest(url: url!))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
After looking at various documentations and videos on the errors I found that the issue was that I was writing my code in the wrong file for the viewController as the viewController that I was targeting was a second one that I created to be access from the original one. Therefore, for anyone else who is completely new development and to xcode and swift. The original viewController.swift file is only for the first viewController. A new viewController.swift file must be created to add code to any subsequently created viewControllers.
Looks like your outlet is not connected properly and also always try to avoid doing force unwrapped. In order to prevent your crash you can use below check:-
guard let url = URL(string: "https://www.google.com") else { return }
myWebView.loadRequest(URLRequest(url: url))
or
if let url = URL(string: "https://www.google.com") {
myWebView.loadRequest(URLRequest(url: url))
}
I have the basic app working fine when doing this, except for some reason my app is just outside of the screen? Does any one know why this would be?
My index page is just basic HTML, linked to a CSS Stylesheet..
and the Xcode:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var webView: UIWebView!
// Load the url into the webview
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let localfilePath = NSBundle.mainBundle().URLForResource("home", withExtension: "html");
let myRequest = NSURLRequest(URL: localfilePath!);
webView.loadRequest(myRequest);
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
If you are not able to do it or you have any issue this is the easy way if you have just only your UIWebView:
I am fetching a request from server and trying to display it in tablview. In this process I am want to hide the spinner after fetching records.
Problem is : Anything associated with self inside block does not work.
#IBOutlet weak var spinner: UIActivityIndicatorView!
#IBOutlet weak var customTableview: CustomTableView!
var widgetArray :NSMutableArray = []
override func viewDidLoad() {
super.viewDidLoad()
print(DataObjects.sharedInstance.mainArray)
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
spinner.hidden = false
spinner.startAnimating()
CustomNetworkHit.networkHitForUrl("http://winjitwinds.cloudapp.net/windapi/windapiservice.svc/getcategorydatapagewise?categoryid=1944&pageno=1", completion: {(arrayResult) -> Void in
// spinner does not stop animating and it does not hide
self.spinner.stopAnimating()
self.spinner.hidden = true
print("Disable the spinner man")
DataObjects.sharedInstance.mainArray.addObjectsFromArray(arrayResult as [AnyObject])
self.widgetArray.addObjectsFromArray(arrayResult as [AnyObject])
self.customTableview.setUpTableView(self.widgetArray)
// UItableview Does not reload Data.
self.customTableview.reloadData()
})
Please specify what you mean by "does not work". Without that it's hard to know for sure but I would guess you are trying to do UI work on a background thread (blocks don't run on the main thread).
Within your block try this:
dispatch_async(dispatch_get_main_queue(), ^(){
// UI CODE GOES HERE
});
In Swift:
dispatch_async(dispatch_get_main_queue()) {
// UI CODE GOES HERE
}
There don't seem to be any SO posts on dismissMoviePlayerViewControllerAnimated in Swift so I guess I'll kick things off.
I have a table cell, when you do a long press on it, it displays a video. When the video ends, my goal is to take the user back to the table view. That last piece is the bit that's not working.
Any help here would be greatly appreciated. I've read through the Apple docs and some posts about this in Objective-C. Seems that the answer is to run dismissMoviePlayerViewControllerAnimated, a method on UIViewController but it's not working.
import UIKit
import MediaPlayer
class ViewController: UIViewController {
var moviePlayer:MPMoviePlayerController!
#IBOutlet weak var longPressView: UIView!
let longPressRec = UILongPressGestureRecognizer()
func longPressedView() {
playVideo()
}
func videoHasFinishedPlaying(notification: NSNotification){
println("Video finished playing")
self.dismissMoviePlayerViewControllerAnimated()
// not returning me to the ViewController
}
func playVideo() {
// get path and url of movie
let path = NSBundle.mainBundle().pathForResource("IMG_8602", ofType:"MOV")
let url = NSURL.fileURLWithPath(path!)
moviePlayer = MPMoviePlayerController(contentURL: url)
// construct the views
moviePlayer.view.frame = self.view.bounds
self.view.addSubview(moviePlayer.view)
moviePlayer.fullscreen = true
// remove controls at top and bottom of video
moviePlayer.controlStyle = MPMovieControlStyle.None
// add event observer for videoHasFinsihedPlaying
NSNotificationCenter.defaultCenter().addObserver(self, selector: "videoHasFinishedPlaying:",
name: MPMoviePlayerPlaybackDidFinishNotification, object: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
longPressRec.addTarget(self, action: "longPressedView")
longPressView.addGestureRecognizer(longPressRec)
longPressView.userInteractionEnabled = true
// 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.
}
}
Your code does not work because you are using MPMoviePlayerController instead of MPMoviePlayerViewController.
You are calling:
self.dismissMoviePlayerViewControllerAnimated()
but there is no MPMoviePlayerViewController to dismiss. That's why nothing happens.
If you prefer to use MPMoviePlayerController (as in the code you posted), after adding manually its view, you also have to manually remove it.
I'm trying to load a URL in my WebView in Swift as soon as the main dialog loads. I'm not sure what I'm doing wrong:
class WebViewController: NSViewController {
#IBOutlet var webView: WebView!
// constants
let webUrl = "https://www.google.com"
let webUA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36"
override func viewDidLoad() {
super.viewDidLoad()
let request = NSMutableURLRequest(URL: NSURL(string: webUrl)!)
request.setValue(webUA, forHTTPHeaderField: "User-Agent")
webView.mainFrame.loadRequest(request)
}
}
When debugging there are no errors or warnings. I think I linked the nib with the objects properly:
I've been playing around with delegations for a few hours now. The page simply doesn't load.
At first I attempted to use applicationDidFinishLaunching, but that went even worse, because the WebView was never finished being created and was nil.
Alright, so change your ViewController to look like this:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var webView: UIWebView!
var urlPath = "http://www.google.com"
func loadAddressUrl() {
let requestUrl = NSURL(string: urlPath)
let request = NSURLRequest(URL: requestUrl!)
webView.loadRequest(request)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
loadAddressUrl()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
And link the #IBOutlet to your web view controller. Example project available if you want.
Source: https://www.youtube.com/watch?v=Rva9ylPHi2w
Turns out I was pointing to the wrong WebView?!
In the hierarchy, it shows up like this:
I needed to use the one that's highlighted, not the inner one. The inner one was used when I control-dragged from Objects into the physical view object in the layout builder. Somehow dragging to this one fixed it.
Swfit 4 version of loadAddressUrl()
private func loadAddressUrl() {
let requestUrl = NSURL(string: url.text!)
let request = NSURLRequest(url: requestUrl! as URL)
webView.load(request as URLRequest)
}