URL not opening on UIWebView? - ios

I try to open a webpage with a IBAction
#IBAction func Start(sender: AnyObject) {
self.viewWebpage("http://www.xxxxx.xx")
}
func viewWebpage(webpage: String)
{
let url = NSURL.fileURLWithPath(webpage)
println(webpage)
let request = NSURLRequest(URL: url!)
self.viewPage.loadRequest(request)
// self.viewPage.reload()
}
The webpage i try to open works when i change in the function the the url to
let url = NSURL(string: "http://www.xxxxxx.xx")
Where is my mistake? The println() prints out the wright url

Issue is with:
let url = NSURL.fileURLWithPath(webpage)
You are converting the web url to file system url (url of a file contained in the system itself). So it won't work, you need to change that to:
let url = NSURL(string: webpage)
According to NSURL Class Reference
+ fileURLWithPath:
Initializes and returns a newly created NSURL object as a file URL
with a specified path. Declaration
Swift
class func fileURLWithPath(_ path: String) -> NSURL?
Objective-C
+ (NSURL *)fileURLWithPath:(NSString *)path
Parameters
path
The path that the NSURL object will represent. path should be a valid
system path. If path begins with a tilde, it must first be expanded
with stringByExpandingTildeInPath. If path is a relative path, it is
treated as being relative to the current working directory.
Passing nil for this parameter produces an exception.
Return Value
An NSURL object initialized with path.
Discussion
This method assumes that path is a directory if it ends with a slash.
If path does not end with a slash, the method examines the file system
to determine if path is a file or a directory. If path exists in the
file system and is a directory, the method appends a trailing slash.
If path does not exist in the file system, the method assumes that it
represents a file and does not append a trailing slash.
As an alternative, consider using fileURLWithPath:isDirectory:, which
allows you to explicitly specify whether the returned NSURL object
represents a file or directory.

Related

AVPlayer - Play from Local URL

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.

How to use loadData to load NSData (o/p of UIImageJPEGRepresentation) into wkwebview?

As part of iOS9 we have the new method loadData() introduced into WKWebView.
I have NSData object that is output of UIImageJPEGRepresentation that I want to render in a WKWebView. Prior to iOS9, in order to render image in wkwebview, I was:
storing nsdata on the local file system as a .jpeg file
create a nsurl with fileWithUrl init method
Call wkwebview.loadRequest(url) where url is the nsurl created in previous step
I was hoping take advantage of the new iOS9 method where I can directly call the wkwebview.loadData(nsdata, MIMEType:"image", characterEncoding:"ASCII", baseURL: NSURL("random"))
I am not able to render the image using the above loadData call. Could be issue with the params I am passing for MIMEType, characterEncoding and baseUrl. Could not find any examples for this method call anywhere.
Notes:
I am not sure what characterEncoding to use when rendering image
The baseUrl cannot be nil and so initialized it to a random url
This works for me:
if let path = NSBundle.mainBundle().pathForResource("Test", ofType: "jpg") {
if let data = NSData(contentsOfFile: path) {
webView.loadData(data, MIMEType: "image/jpeg",
characterEncodingName: "", baseURL: NSURL(string: "")!)
}
}
The characterEncodingName and baseURL look a bit odd but I doubt they are relevant for loading image/jpeg type data.
This might be a late answer, we had similar issue in one of our projects, one way you can solve this is using html's power by embedding the content inside html.
func loadDataContent(data:Data,mimeType:String) {
let urlStr = "<iframe width=\"100%\" height=\"100%\" src=\"data:\(mimeType);base64,\(data.base64EncodedString())\"></iframe>"
webBrowser?.loadHTMLString(urlStr, baseURL: nil)
}

Curious whether fileUrl of CKAsset can change with time?

I am caching CKRecord on client and fileUrl of CKAsset too. Can fileUrl change from time to time? Asset / data itself is not changing.
The fileURL of an asset will not change, but if this is an asset you downloaded from the server the data is only guaranteed to exist at that location until the completion block of the operation is called. After that point the asset's backing file may be cleaned up at any time to free up disk space.
After downloading an asset from the server you should move or copy the backing file to another location in your application's container if you'd like to keep it.
The archived URL is a full path, but since iOS 8 or so the container URL that your app uses to store its files changes everytime the app starts.
So the archived URL is wrong.
This seems like a bug in the way CKAssets are archived to me, they should be archiving and unarchiving the partial path relative to the app's container. Not the full path.
I guess I'll file a radar.
Edit: here's a solution:
extension CKAsset {
var url: URL? {
let path = fileURL.path
if FileManager.default.fileExists(atPath: path) {
return fileURL
} else if let index = path.range(of: "/Library/Caches/") {
// archived CKAssets store full-path URLs but since iOS 8 or so
// the path of our container (home-dir) changes every time we are
// started. So the full path is useless. Try to mangle it.
let suffix = String(path.suffix(from: index.upperBound))
let adjustedUrl = URL.caches/suffix
if FileManager.default.fileExists(atPath: adjustedUrl.path) {
return adjustedUrl
}
}
return nil
}
}
public extension URL {
static var caches: URL {
return FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first ?? URL(fileURLWithPath: "")
}
}

Swift - pathForResource inDirectory parameter

I'm making a very simple app that uses a UIWebView to display a pdf map that can be zoomed in on, panned, etc.
However, when creating a target url for the pdf, the pathForResource call isn't working right. This is my code:
var targetURL : NSURL = NSBundle.mainBundle().pathForResource(filename, ofType: type)
I get an error on the parentheses before "filename", that says Missing argument for parameter 'inDirectory' in call. I tried adding an argument for this:
var targetURL : NSURL = NSBundle.mainBundle().pathForResource(filename, ofType: type, inDirectory: "Map")
I don't know what to put for inDirectory, because I don't know what the directory is - I added the file to my project and it is in the same folder as my ViewController.swift file. Anyway, it doens't really matter, because I get the following error in the same place, Extra argument 'inDirectory in call.
What do I do?
pathForResource() does not return a NSURL object, but a String?. Declare your variable accordingly and it should work.
var targetURL : String? = NSBundle.mainBundle().pathForResource(filename, ofType: type)
Or, of course, if you would rather - just use URLForResource() instead.
var targetURL : NSURL? = NSBundle.mainBundle().URLForResource(filename, withExtension: type)
I was having this same problem. In my case it was because my variable (in your case type) needed to be unwrapped. Adding a bang ! made the error go away and made the code execute.

Load file in Today extension

I've been trying to create a Today extension that needs access to a .plist file in the documents directory. I have setup the App group for both the app and the extension.
While I have seen examples for NSUserDefaults, I couldn't find anything for accessing files.
I tried accessing the file like this (which works in the app itself)
let paths = NSSearchPathForDirectoriesInDomains(
.DocumentDirectory, .UserDomainMask, true)
let documentsDirectory = paths[0] as String
let filePath = "\(documentsDirectory)/config.plist"
if NSFileManager.defaultManager().fileExistsAtPath(filePath) // false
{
…
}
But I get the following error messages in the console:
Warning: CFFIXED_USER_HOME is not set! It should be set to the simulated home directory.
Failed to inherit CoreMedia permissions from 59919: (null)
The documentation says something about using NSFileCoordinator and NSFilePresenter. I couldn't find out how to use them though. I'm sure I'll need to tell them the app group identifier somewhere but I don't where.
I got it to work. Since I don't need to write the file from the extension, I don't think I need to use NSFileCoordinator. Turns out NSFileManager has a method containerURLForSecurityApplicationGroupIdentifier() for retrieving the container URL.
let manager = NSFileManager()
let containerURL = manager.containerURLForSecurityApplicationGroupIdentifier("group.MyGroupIdentifier")
let filePath = "\(containerURL.path)/config.plist"
let settings = NSDictionary(contentsOfFile: filePath)

Resources