I think I know what was my problem but I couldn't find a solution for it.
On my app, you can see that there is a YouTube video, but when you click on it, it won't play the video. Here's the line of code that may cause the issue:
webView.loadHTMLString(partyRock.videoURL, baseURL: nil)
I think that sending nil to the baseURL may cause the issue, but I'm not sure what to replace with.
Thanks
Why are you using loadHTMLString? This property sets the main page content and base URL and I don't think you want to do that.
Use this instead:
let requestURL = URL(string: partyRock.videoURL)
let request = URLRequest(url: requestURL!)
webView.loadRequest(request)
let request = URLRequest(url: URL(string: "https://www.youtube.com/watch?v=KBcIKsJBo2Y")!)
webView.loadRequest(request)
Related
I am developing an application(Swift 3 using UIWebview). I need to load webpages into webview and save some webpages into cache. If there is not internet user will able to see those pages. But I am confused on how to save whole webpage in cache. The main thing is we need to show pages back even if there is not internet.
I used the following documention : http://nshipster.com/nsurlcache/
and https://developer.apple.com/reference/foundation/urlcache
let url = NSURL(string: load_url1)
let request = NSURLRequest(url: url as! URL,cachePolicy: NSURLRequest.CachePolicy.returnCacheDataElseLoad, timeoutInterval: 60)
self.webView.loadRequest(request as URLRequest);
Has anyone implemented this before. Please provide some demo code as this is my first attempt on cache
Just use
let url = URL(string: urlString)
var urlRequest = URLRequest(url: url!)
urlRequest.cachePolicy = .returnCacheDataElseLoad
webView.loadRequest(urlRequest)
Surprisingly i have not been able to find an answer to this despite many searching.
I have a file that has been cached, i can retrieve the cache directory and file name which i believe to be the url?
this is code to get the file and then play it
let cachedFilePath = getCachedFilePath.result as! String
audioFileURL = cachedFilePath
self.audioPlayerItem = AVPlayerItem(url: NSURL(string: audioFileURL!) as! URL)
This is what is returned if i print audioFileURL:
/Users/Genie/Library/Developer/CoreSimulator/Devices/A2FB00CE-B018-4FDF-9635-35FD6678DF8D/data/Containers/Data/Application/E18B5E89-B973-4277-AA5C-1378C69D80CD/Library/Caches/Parse/PFFileCache/7e4a8fc0eb37b655b859e4959f986da2_The%20Name%20of%20the%20Wind%2017-92.mp3
The player loads but it never plays, It just sits there spinning. so i am wondering if i am passing the url to the player correctly?
i read on one thread to use file:// before it but that didn't work.
In the place where you're creating an NSURL, you have the replace the argument name string to fileURLWithPath
Change
NSURL(string: audioFileURL!)
to
NSURL(fileURLWithPath: audioFileURL!)
Also, why are you casting NSURL to URL ? Why not use URL directly?
try like this,i hope it will work for you.
self.audioPlayerItem = AVPlayerItem(url:NSURL(fileURLWithPath: audioFileURL!) as! URL)
AVPlayerItem(url:URL(fileURLWithPath: Bundle.main.path(forResource: "filename", ofType: "mp4")!))
And make sure your video is added to the bundle:
project root > your Target > Build Phases > Copy Bundle Resources.
I'm creating a html5 app, embed in UIWebView. I have delegate webview to controller, and on shouldStartLoadWithRequest, I'm looking for url pattern to open or not on external browser.
It's work perfect!
But when phone has no connection, I'm loading local html file. Because shouldStartLoadWithRequest return FALSE on first request, offline.html not loading
Anyone has do that?
Try this immediately after set path :
do {
let path = NSBundle.mainBundle().pathForResource("offline", ofType: "html", inDirectory:"offline")
let string = try String(contentsOfFile: path!, encoding:NSUTF8StringEncoding)
webView.loadHTMLString(string, baseURL: NSURL(string: "http://"))
} catch {
print(error)
}
or
let url = NSURL(fileURLWithPath:NSBundle.mainBundle().pathForResource("offline", ofType:"html", inDirectory: "offline")!)
let request = NSURLRequest(URL: url);
webView.loadRequest(request);
I tried it and it works.
Make sure your "offline" directory is a folder (BLUE) and not a group (YELLOW).
Hope this help.
I found the problem. I'm not triggering error -1003 (no host found)! removing switch work perfectly!
I use WKWebview to load a URL.
let webView = WKWebview()
let request: NSMutableURLRequest = NSMutableURLRequest(URL: url!)
webView.loadRequest(request)
How can I detect if the link the webView should load is broken?
You can use canOpenUrl method:
UIApplication.sharedApplication().canOpenURL(url)
It will do the url validation and if the link is ok it returns true.
It's mostly use before you call:
UIApplication.sharedApplication().openURL(url)
to make sure this link can be open in safari but it should help you here too.
Make sure the link starts with http:// or https://.
Edited:
It will just check is the link is a correct url.
If you want to see the page is offline, authorisation issues, etc. you can implement WKNavigationDelegate protocol and check out this method:
- webView:didFailNavigation:withError:
this should give you more info.
It's always good idea to use: str.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAl‌​lowedCharacterSet())!
it make sure that you don't pass a character which are not allowed in URL.
Edited 2:
To detect the status code you can try to implement:
- webView:decidePolicyForNavigationResponse:decisionHandler:
the navigation response is an NSURLResponse instance but
whenever you make an HTTP request, the NSURLResponse object you get back is actually an instance of the NSHTTPURLResponse class so you should cast it to NSHTTPURLResponse. That should give you a statusCode.
In the last line in the method you should call handler, for example decisionHandler(WKNavigationResponsePolicyAllow).
Ref: Answer exists here
if let url = NSURL(string: yourUrlString) {
var canOpen = UIApplication.sharedApplication().canOpenURL(url)
}
If you want to check if url string is correct and valid - just create NSURL object, if path contains error it will cast to nil:
let string = "http://google.com"
let url = NSURL(string: string)
let brokenString = "http:\\brokenurl.12"
let brokenUrl = NSURL(string: brokenString) // nil - it's not valid!
If you have implemented NSURLConnectionDelegate then below solution can be used.
didFailWithError method of NSURLConnectionDelegate can be used for this.
This method get called if an error occurs during the loading of a resource.
Can refer to below link
https://developer.apple.com/documentation/foundation/nsurlconnectiondelegate/1418443-connection
I am grabbing images from instagram and am receiving urls like "http://instagram.com/p/1JiWygQUSu/media/?size=l" the issue is this url directs to "https://scontent-lax3-1.cdninstagram.com/hphotos-xfa1/t51.2885-15/e15/1527608_451589571655110_1239072675_n.jpg" I need the file extension to properly cache the image on a user device.
The first url is redirecting to the second. I need a way to retrieve the second url from the first.
Tried using this code but it just returns the original url:
let urlString = "http://instagram.com/p/1JiWygQUSu/media/?size=l"
let request: NSMutableURLRequest = NSMutableURLRequest(URL: NSURL(string:urlString)!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringCacheData, timeoutInterval: 15.0)
request.HTTPMethod = "HEAD"
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {
(response, data, error) in
print("instaResponse \(response?.URL)")
})
Try looking at NSURLSessionTaskDelegate method
- URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler: Documentation here.
You should be able to handle the redirect there and cache the image. Alternatively, you can try using SDWebImage or AFNetworking which have image caching built in, and probably handle the redirect case already.