Swift 2.0 not downloading images to UI ImageView - uiimageview

Team,
Weird problem. I took the plunge into Swift 2. So far it's pretty great and while I've had to do some code fixup, it hasn't been too bad.
Then I hit this weird bug (I think it's a bug?)
I can't seem to download images to a UIImage View. I've tried a few different approaches. But none seem to work. Has anyone been able to get this to work (populating image views from a URL) in Swift 2?
Here's my latest try:
//
// ViewController.swift
// uiimage_from_url
import UIKit
class ViewController: UIViewController {
#IBOutlet var image_element: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
load_image("http://s3.evcdn.com/images/block250/I0-001/016/377/706-0.jpeg_/jazz-cam-graduation-2015-06.jpeg")
}
func load_image(urlString:String)
{
let imgURL: NSURL = NSURL(string: urlString)!
let request: NSURLRequest = NSURLRequest(URL: imgURL)
let response:NSURLResponse = NSURLResponse()
let data:NSData = NSData()
let error:NSError
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler:{ response, data, error in /* Your code */ })
self.image_element.image = UIImage(data: data)
}
}

So after being downvoted for the question, I assumed I was going to have to answer it myself. Thanks down voters :(
Apparently iOS 9 and I'm guessing OSX 10.11 requires TLSv1.2 SSL for all hosts that you plan to request data from. Unless.... you specify exception domains in your application's Info.plist file.
The easy/cheap fix is to do something like this:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
I'm sure there's a better/cleaner way. But this will re-enable downloading any image from any website.

Related

Loading a URL with a WKWebView in macOS

I've made a fresh mac app project with the following code in the ViewController.
import Cocoa
import WebKit
class ViewController: NSViewController {
var loginWebView: WKWebView!
override func viewDidLoad()
{
super.viewDidLoad()
self.loginWebView = WKWebView(frame: self.view.frame)
self.view.addSubview(loginWebView)
let urlReq = URLRequest(url: URL(string: "https://apple.com/")!)
self.loginWebView.load(urlReq)
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
For some reason when I launch the app the web view isn't loading the website. Why is this? I've been developing on iOS for years and am just getting started with macOS.
EDIT: Update loading a local file wouldn't work either
self.loginWebView.loadFileURL(fileURL, allowingReadAccessTo: dirURL)
The problem was that I had not enabled Incoming and Outgoing Connections in my app's sandboxing settings. I discovered this by reverting to using the legacy WebView and then getting an error code in the console. WKWebKit will not print error messages making something really simple incredibly difficult and confusing!. Apple really needs to fix that

Swift: Build succeeds, a blank app window and this message appear: Failed to set (contentViewController) user defined inspected property on (NSWindow)

I tried to create a simple Complex Number Calculator using classes. My application has compiled successfully, but when I ran it, a blank window appeared instead of a window with all my buttons, labels etc. and I got this message in the output window:
2016-03-08 22:20:42.499 Complex Numbers[30404:2328250] Failed to set
(contentViewController) user defined inspected property on (NSWindow):
Cannot create BOOL from object <_NSControllerObjectProxy:
0x6000000022c0> of class _NSControllerObjectProxy
This is my ViewController class code. It involves a complexNumber class, which I didn't submit here:
class ViewController: NSViewController {
#IBOutlet var Screen: NSView!
var a = complexNumber();
#IBOutlet var realValue: NSTextField!
#IBOutlet var imaginaryValue: NSTextField!
#IBOutlet var resultLabel: NSTextField!
#IBAction func lengthResult(sender: AnyObject) {
let r = NSString(string: realValue.stringValue).doubleValue;
let i = NSString(string: imaginaryValue.stringValue).doubleValue;
a = complexNumber(real: r, imaginary: i);
resultLabel.stringValue = String(a.trigonometric());
}
#IBAction func trigonometryResult(sender: AnyObject) {
let r = NSString(string: realValue.stringValue).doubleValue;
let i = NSString(string: imaginaryValue.stringValue).doubleValue;
a = complexNumber(real: r, imaginary: i);
resultLabel.stringValue = String(a.length());
}
#IBAction func operation(sender: AnyObject) {
a = complexNumber(real: NSString(string: realValue.stringValue).doubleValue, imaginary: NSString(string: imaginaryValue.stringValue).doubleValue);
realValue.stringValue = ""
imaginaryValue.stringValue = "";
let b = complexNumber(real: NSString(string: realValue.stringValue).doubleValue, imaginary: NSString(string: imaginaryValue.stringValue).doubleValue)
switch sender.stringValue {
case "+": a = a.sum(b)
case "-": a = a.dif(b)
case "x": a = a.mul(b)
case ":": a = a.div(b)
default: a = a.sum(complexNumber())
}
}
#IBAction func displayResult(sender: AnyObject) {
resultLabel.stringValue = String("\(a.real) + i*\(a.imaginary)");
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
}
I found a similar thread here, but I don't think it's what I was looking for.
Can you help me, please?
Another reason - when you setup wrong binding.
Example of my error:
Failed to set (contentViewController) user defined inspected property on (NSWindow): [<NSProgressIndicator 0x10111b890> valueForUndefinedKey:]: this class is not key value coding-compliant for the key Enabled.
To solve this you need to delete the binding here:
For me was a timing issue I guess. All begins after I added an SFAuthorizationView some days ago, and I discovered that thanks to a bug report, where also was clear that this is happening on older OSes like Sierra, but it is fine, instead, in 10.13+.
Moving some code from viewDidLoad() to viewDidAppear() the problem gone.
Basically I'm just waiting to call any related method of the problematic view later the viewcontroller content view is declared as loaded. Clearly a an Apple problem fixed in new OSes. So after instantiate the nib/xib/storyboard involved I think anyone encounter problems like that should firstly show the view and then customise it. Just my testimony.
I had this problem and figured it out.
In my view I had a user defined property (if you look at the top of your view where you have view controller and first responder you should see it's icon next to it).
Simply delete it and run your application.
Hope this helps!
I you've created an app with a"storyboard" i.e. if there's a storyboard file with your views and windows in it, then there's one of two things missing:
1) If theres a main window and a view that should be it's main view, then right click - drag from the window controller to the view that should be the main view.. When the popup happens, click on "content view" i.e. like follows:
Check out my video example
If this fails, then I'll dig out plan two :)
How this helps!!
Ade.
One thing that may help others, I saw the same message, it looked like the contentViewController was the problem, but it turned out it was another component in something I was writing was failing. It seems the window manager catches all exceptions, not just window exceptions, and prints this deceptive message. What worked for me is stepping through to find component is not loading.
This happens when there is an error or exception in ViewDidLoad.
Ensure that error is cleared and your UI will load fine and u wont get this message.

WKWebView Cache manifest not working IOS8

Cache manifest works fine and events fired in safari in IOS 8. Not working at all in WKWebView anyone else solve this issue?
import UIKit
import WebKit
class ViewController: UIViewController {
#IBOutlet var containterView : UIView! = nil
var webView : WKWebView?
override func loadView(){
super.loadView()
self.webView = WKWebView()
self.view = self.webView!
}
override func viewDidLoad() {
super.viewDidLoad()
var url = NSURL(string:"http://html5demos.com/offlineapp")
var req = NSURLRequest(URL:url)
self.webView!.loadRequest(req)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
The application cache comes back as supported if I were to use html5test.com
EDIT:
window.applicationCache does not return undefined either when loaded from WKWebView
console.log("Initializing Page");
if (window.applicationCache == undefined){
console.log("Application cache not suported!");
updateSplash();
}
console.log(window.applicationCache); returns: DOMApplicationCache
EDIT 2:
if (typeof window.applicationCache.update === 'function'){
console.log("Application has method update");
console.log(window.applicationCache.update); //shows swapCache() and update() methods
window.applicationCache.update();
}
window.applicationCAche.update() throws Error: InvalidStateError: DOM Exception 11: An attempt was made to use an object that is not, or is no longer, usable.
Just for the record, this question appears to have been asked on and linked from the Apple Developer Forums. The official response from Apple is that the HTML5 Application Cache functionality is not available in WKWebView:
The offline application cache is not enabled in WKWebView. Feel free to request that it be made available via https://bugreport.apple.com.
I think you are trying to solve the same problem as I do. This is what I do.
Save the start page of your web app into one HTML file(index.html), embedding everything (CSS, JS, images as base 64, icon fonts). And add that file into your Xcode project.
Start the app by reading the content of the HTML file and load it in your WKWebView. You can set the base as the same url you are supposed to start with. This way, it'll be as if the web app is opened on your web site.
The benefit is that your app will always start even when the user's network isn't good. Here's the SWIFT code that I use, courtesy of Matt Neuberg (https://books.google.com/books?id=wLaVBQAAQBAJ&pg=PT669&lpg=PT669&dq=addConstraints+wkwebview&source=bl&ots=7trE7MR1zR&sig=VT6GDBGbDw9dh89wDb5Uajd4gUY&hl=en&sa=X&ei=cyyeVNH4MM3ToATukoDgAQ&ved=0CDkQ6AEwBA#v=onepage&q=addConstraints%20wkwebview&f=false). If you want the full source code, please let me know and I'll post it on Github.
let templatepath = NSBundle.mainBundle().pathForResource("index", ofType: "html")!
let base = NSURL(string:"http://m.ftchinese.com/iphone-2014.html#iOSShare")
var s = NSString(contentsOfFile:templatepath, encoding:NSUTF8StringEncoding, error:nil)!
self.webView!.loadHTMLString(s, baseURL:base)

Swift EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) with WebView

I try to make simple OSX application with WebView. I am new in Swift, and have some errors:
it's my WebView delegate file:
class WebViewControllerDelegate: NSObject{
#IBOutlet var webview: WebView!
override init()
{
super.init()
self.webview.frameLoadDelegate = self
let url = NSURL(string: "http://google.com")
let request = NSURLRequest(URL: url);
self.webview.mainFrame.loadRequest(request)
}
func didFinishLoadForFrame()
{
println("ok:")
}
}
I try to run this, but have EXC_BAD_INSTRUCTION error at line where I set frameLoadDelegate to self. I think it's error with web view outlet, but i can't fix it.
self.webview is nil, and i don't know why...
Views in Xib / Storyboard files are not loaded nor connected during initialization. That is why self.webview is nil in your code.
You really should not attach the IBOutlet directly to your "delegate". Instead, connect it to your view controller and have the view controller set it on the delegate. You should do that in viewDidLoad because that is when you can guarantee all of the objects have been created and connected.
I had same error before. I give you a suggestion for solve this error. Do following things...
1. Click on the View Controller open the connection inspector.
See this...
2. And then you have to double check on the connection inspector window and find something contain like following image...
3. Then you have to delete one outlet. According to my one I have to delete below one... finally solved one...
Then run the code...

webViewDidFinishLoad not firing called working

(Swift, iOS8, Xcode6, iPhone/iPad)
webViewDidFinishLoad is not being called, is not firing, and is not working.
Yes, I have set the containing view controller as the delegate. I CTRL-mousedowned on the UIWebView, dragged up to the little yellow circle representing the view controller, and released. A right-click on the UIWebView object shows that the delegate is set.
Yes, I did implement UIWebViewDelegate in my class declaration, like so:
class Paragraph: UIViewController, UIWebViewDelegate {
Yes, I did restart Xcode, and test on both the simulator and an actual iPhone 4S.
The request looks like this:
#IBOutlet var paragraph : UIWebView = nil
var r = NSBundle.mainBundle().pathForResource("cheddar", ofType: "htm")
var u = NSURL(fileURLWithPath: r)
paragraph.loadRequest(NSURLRequest(URL: u))
The callback function looks like this:
func webViewDidFinishLoad() {
println("webViewDidFinishLoad")
}
I got it. The callback was missing a parameter. For posterity:
func webViewDidFinishLoad(webView: UIWebView!) {
Note the webView: UIWebView! parameter
In this case, perhaps even more important, is the way I found the bug. I created an entirely new view controller, and pieced it back together, carefully checking at each step to make sure that I didn't miss anything.
When the Intellisense popup showed the function with the parameter, I saw my error.
NOTE: In Swift 2.2, the UIWebViewDelegate protocol specifies a different optionality:
webView: UIWebView.
webView: UIWebView! spawns a warning.

Resources