There are several posts on this subject, but I can't see the answer to this problem in them. The following lines produce the title error:
let pdf_url = NSURL.fileURL(withPath: inputfile)
let pdf_doc = PDFDocument.init?(url: pdf_url) as! URL
I understand that the init method can take a variety of data types, but surely I've made it pretty clear that I want a URL.
Error message is:
error: ambiguous reference to member 'init(url:)'
A problem which may be related is that Xcode occasionally tells me to use URL, not NSURL, in the first line, but then complains that URL doesn't have the fileURL method.
(I also tried CGPDFDocument, but that wanted a CFURL, and wouldn't accept NSURL, even though they are supposed to be "toll-free bridged".)
The error occurs because you (try to) cast PDFDocument to URL.
You probably mean
PDFDocument.init?(url: pdf_url as! URL)
But the recommended Swift 3 syntax is
let pdfURL = URL(fileURLWithPath: inputfile) // returns a non-optional URL
let pdfDoc = PDFDocument(url: pdfURL)
Please use – Swift – camel case variable names rather than – javascript / php – snake case.
Use URL:
let pdf_url = URL(fileURLWithPath: inputfile)
Related
When calling my function to fetch some locations from an API I'm getting the error "Type of expression is ambiguous without more context".
As I'm relatively new to iOS development and swift I have to ask you guys. Hope its just some simple thing I've overseen. I already searched the web, but nothing helped.
Thank you in advance!
Here is how I'm calling the function:
fetchLocation(latitude: latitude, longitude: longitude, locationsCompletionHandler: {
shopSites in
ForEach (shopSites){ }
})
And here is the function:
func fetchLocation(latitude: Double, longitude: Double, locationsCompletionHandler: #escaping ([ShopSite]) -> Void) {
let semaphore = DispatchSemaphore (value: 0)
let domain = "http://e2cadda8d178.ngrok.io/api/v1/"
let urlString = domain + "public/location/" + String(latitude) + "/" + String(longitude) + "/50"
//let url = URL(string: "e2cadda8d178.ngrok.io/api/v1/public/location/66.68994/10.249066/50")!
let url = URL(string: urlString)!
var request = URLRequest(url: url,timeoutInterval: Double.infinity)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request) { json, response, error in
guard let json = json else {
print(String(describing: error))
semaphore.signal()
locationsCompletionHandler([])
return
}
let str = String(decoding: json, as: UTF8.self)
print(str)
let shopSites: [ShopSite] = try! JSONDecoder().decode([ShopSite].self, from: json)
print(shopSites.count)
semaphore.signal()
locationsCompletionHandler(shopSites)
}
task.resume()
semaphore.wait()
Let me now if you need further details.
So, the debug information you get in Swift is based on the output from the compiler. Unfortunately, that means sometimes you get really terrible error messages like this when the compiler cannot figure out what you're trying to do.
I think your problem boils down to the fact that you're using ForEach which is a type of view from SwiftUI when you really want a simple for loop like:
for site in shopSites.
You could also do shopSites.forEach { }, which would be another way of iterating over that array.
Anyways, I think using a view that looks like it is named like it should be a loop where you really want some kind of actual loop construct is your problem here.
In general, when you get an error like that there's no one answer. Take a step back, try to add more specific type annotations, or rephrase what you're trying to say and usually a better error message will shake out.
How can I find out specific character from URL String variable using Swift 3?
i want to get the value out of the URLlink(image is given) user_lati,user_long,destination_lat,destinaton_long and save it.
Can any one give me the solution for this?
I have given a couple of examples below. You should really check the documentation for String, URL and Collections
let urlString = "https://www.example.com/search?q=test&user=john"
let url = URL(string: urlString)!
print(url.query) // q=test&user=john
print(urlString.index(of: "?")?.encodedOffset) // 30 - index of ?
print(url.absoluteString.index(of: "?")?.encodedOffset) // same as above
I'm having trouble converting URL to string. The getScreenShotDirectory() path is file:///Users/Pat/Desktop/.
My goal is to convert it to String, so the path can look like /Users/Pat/Desktop/
let urlString = getScreenShotDirectory()
let pathURL = URL(string: getScreenShotDirectory())! // error
I would gladly provide more code if needed.
It appears that your getScreenShotDirectory() method is already a URL. So you get the error trying to pass a URL to the URL(string:) method which, of course, expects a String, not a URL.
The simple solution is to properly convert the URL to a path string:
let pathURL = getScreenShotDirectory() // URL
let pathString = pathURL.path // String
EDIT
https://www.someurl.com/search?&access_token=1,84,848473938;848483,83&_json={"key1":"value1","key2":"value2"}
When declaring a URL that has a JSON string, I obviously need to use braces _json={ } and qoutes \"key1\":\"value1\"
NSURL(string: String), however, magically becomes nil if either of these characters are included in the string.
So as answered correctly here: NSURL is returning nil for a valid URL, I tried using:
let url = NSURL(string: url.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!)
But I believe that's deprecated since it was before Swift 2 was released and I am getting the error: cannot convert value of Type NSCharacterSet to expected argument type NSStringEncoding (aka UInt)
So I tried using
let url = NSURL(string: url.stringByAddingPercentEncodingWithAllowedCharacters(NSUTF8StringEncoding)!)!
and while that did allow NSURL to have a value instead of nil, it did not return the expected results, so something is still wrong.
I know that the format is correct, because if I type the URL string manually in a browser, I get the expected result. If i copy/paste the encoded version from Xcode, it gives me the wrong result as did Swift when encoding as shown above.
Any insight would be much appreciated.
You can modify a mutable character set to remove an allowed character: since you want the commas to be encoded, remove the comma from the URLQueryAllowedCharacterSet before using it.
In Swift 2, we need to dance with NSMutableCharacterSet like this:
let sourceURL = "https://www.someurl.com/search?&access_token=1,84,848473938;848483,83&_json={\"key1\":\"value1\",\"key2\":\"value2\"}"
let charSet = NSMutableCharacterSet()
charSet.formUnionWithCharacterSet(NSCharacterSet.URLQueryAllowedCharacterSet())
charSet.removeCharactersInString(",")
let url = NSURL(string: sourceURL.stringByAddingPercentEncodingWithAllowedCharacters(charSet)!)
print(url!)
Prints:
https://www.someurl.com/search?&access_token=1%2C84%2C848473938;848483%2C83&_json=%7B%22key1%22:%22value1%22%2C%22key2%22:%22value2%22%7D
To do the same thing with Swift 3 we're using the CharacterSet struct instead of NSMutableCharacterSet but it's the same idea:
var charSet = CharacterSet()
charSet.formUnion(.urlQueryAllowed)
charSet.remove(",")
if let encoded = sourceURL.addingPercentEncoding(withAllowedCharacters: charSet) {
if let url = URL(string: encoded) {
print(url)
}
}
Appending the .txt file component to the URL path doesn't work:
var error:NSError?
let manager = NSFileManager.defaultManager()
let docURL = manager.URLForDirectory(.DocumentDirectory, inDomain:.UserDomainMask, appropriateForURL:nil, create:true, error:&error)
docURL.URLByAppendingPathComponent("/RicFile.txt") <-- doesn't work
via debugger:
file:///Users/Ric/Library/Developer/CoreSimulator/Devices/
<device id>/data/Containers/Data/Application/<app id>/Documents/
Writing a String using docURL to a file doesn't work because of the missing file name.
Reason (via error):
"The operation couldn’t be completed. Is a directory"
So Question: Why doesn't the following work?
docURL.URLByAppendingPathComponent("/RicFile.txt")
URLByAppendingPathComponent: doesn't mutate the existing NSURL, it creates a new one. From the documentation:
URLByAppendingPathComponent: Returns a new URL made by appending a
path component to the original URL.
You'll need to assign the return value of the method to something. For example:
let directoryURL = manager.URLForDirectory(.DocumentDirectory, inDomain:.UserDomainMask, appropriateForURL:nil, create:true, error:&error)
let docURL = directoryURL.URLByAppendingPathComponent("/RicFile.txt")
Even better would be to use NSURL(string:String, relativeTo:NSURL):
let docURL = NSURL(string:"RicFile.txt", relativeTo:directoryURL)
With the update to the Swift language, the suggested call to manager.URLForDirectory(...) no longer works because the call can throw (an exception). The specific error is "Call can throw, but it is not marked with 'try' and the error is not handled". The throw can be handled with the following code:
let directoryURL: NSURL?
do
{
directoryURL = try manager.URLForDirectory(.DocumentationDirectory,
inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
}
catch _
{
print("Error: call to manager.URLForDirectory(...) threw an exception")
}