iOS8, Swift: fileURLWithPath - missing argument for parameter error - ios

I am trying to append subdirectory to documents directory using method:
class func fileURLWithPath(path: String) -> NSURL?`
code:
let applicationDocumentsDirectory:String = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
let storesDirectory:NSURL = NSURL.fileURLWithPath(applicationDocumentsDirectory).URLByAppendingPathComponent("Stores")
Getting error
missing argument for parameter 'isDirectory' in call.
I don't really get it, why compiler requires this parameter? It isn't mentioned in the interface?
Thnanx in advance

The problem is that you're trying to chain methods when there are optionals in the chain.
NSURL.fileURLWithPath(applicationDocumentsDirectory) returns NSURL? type. When you try to execute method URLByAppendingPathComponent on it, it throws a compiler error.
I know it's kind of sucks that the compiler error is totally unrelated to the real cause, but it's just a beauty of current Swift version.
Use ! to unwrap and it's gonna work properly:
let storesDirectory:NSURL =
NSURL.fileURLWithPath(applicationDocumentsDirectory)!
.URLByAppendingPathComponent(NFConstants.NFCoreDataStringIdentifiers.CoreDataStoresPathComponent.rawValue)
Of course force unwrapping the optional is potentially crashy, so even better use if let idiom:
if let baseUrl = NSURL.fileURLWithPath(applicationDocumentsDirectory) {
let storeURL = baseUrl.URLByAppendingPathComponent(NFConstants.NFCoreDataStringIdentifiers.CoreDataStoresPathComponent.rawValue)
}

Related

Cannot convert value of type String to specified type NSManagedObjectContext, While converting from Swift 2.3 -> 3.2

I need Help. While conversion from Swift 2.3 -> 3.2 I received below error. I'm not able to resolve this error.
Below is my coding stuff, where I'm facing some issues.
Error1 : Cannot convert value of type String to specified type
NSManagedObjectContext**
Error2 : Cannot convert return expression of type URL to return type URL.
class func persistentFileURL(_ name: String, enclosingDirectoryName: String) -> Foundation.URL {
let directoryURL = self.directoryForPersistentStorage(enclosingDirectoryName)
let urlPath = directoryURL.path
let filePath: NSManagedObjectContext = (urlPath as NSString).appendingPathComponent(name) //Error1 : Cannot convert value of type String to specified type NSManagedObjectContext
return URL(context: filePath) // Error2 : Cannot convert return expression of type URL to return type URL.
}
Note : URL is separate Class declared to handle this : URL_Class
Please help me. I'm very new to iOS. Not able to understand this type of error.
let filePath: NSManagedObjectContext = (urlPath as NSString).appendingPathComponent(name)
should read
let filePath: String = (urlPath as NSString).appendingPathComponent(name)
Error 2:
URL doesn't have any constructor using context:. Try to use init(fileURLWithPath:) instead (which expects a string, so you need to make filePath an instance of string instead of an NSManagedObject).
See official docs on URL from Apple here.
EDIT
Seeing as you are returning a custom URL object (subclass of NSManagedObject), you need to change the return type of your function.
From -> Foundation.URL to -> URL. I'd suggest to rename your custom URL subclass to something else, since this name is already used by Apple and will probably cause some namespace issues (compiler will get confused and you will get errors).

Converting string (Contains json string) to NSURL in swift

I have PAI its Implemented in .NET.
one of the web service url is like this
http://123.321.33/UploadCitizenImage?jsonString={\"Mobile\":\"12345678\", \"fileName\":\"7661832460_05072018.png\"}
while converting above string to URL in swift, app going crash.
for more info check this
The URL(string:) initializer returns an optional since the parsing of the string may fail. In that case, nil is returned. That's exactly what's happening here since the string you are providing is not a valid URL: there are several characters in the query that are not allowed there and need to be replaced: { as %7B, " as %22, space as %20 and } as %7D.
So the initializer returns nil. Next thing you do is force unwrap via the ! operator. But force-unwrapping a nil is illegal and is why you get the crash.
If you want to create an URL, please look into the URLComponents class which does all the necessary escaping for you so you don't need to care about it. The queryItems property is of particular interest for you, it's an array of URLQueryItem.
Please do something like that,
let jsonString = "jsonString={\"Mobile\":\"12345678\", \"fileName\":\"7661832460_05072018.png\"}" as String
let urlEncoadedJson = jsonString.addingPercentEncoding(withAllowedCharacters:.urlHostAllowed)
let urls = NSURL(string:"http://123.321.33/UploadCitizenImage?\(urlEncoadedJson ?? "")")
First convert your json into encodedJson then add into your url.
Do let me know if there is some issue.
You can try this,
let string = "http://123.321.33/UploadCitizenImage?jsonString={\"Mobile\":\"12345678\", \"fileName\":\"7661832460_05072018.png\"}"
let escapedString = string.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
let url = URL(string: escapedString!)!
print(url)
Output will be like this,
http://123.321.33/UploadCitizenImage?jsonString=%7B%22Mobile%22:%2212345678%22,%20%22fileName%22:%227661832460_05072018.png%22%7D

Cannot invoke initializer for type 'URL' with no arguments - Swift 3

Receive error:
Cannot invoke initializer for type 'URL' with no arguments
Following is the code -
var databasePath = URL()
I have declare this variable globally. Also tried for
var databasePath: URL!
if let url = NSURL().absoluteURL { //error 1- Consecutive declarations on a line must be separated by ';'
databasePath = url //error2 - Variable used within its own initial value
}
Receive above 2 errors if write above code as replacement of var databasePath = URL() .
I am beginner in Swift. Please let me know the solution.
The URL initializer must have an argument.
Basically there are two types:
An URL in the file system
let databaseURL = URL(fileURLWithPath:"/path/to/file.ext")
An URL with an explicit scheme (e.g. http, ftp etc)
let databaseURL = URL(string:"http://myserver/path/to/file.ext")!
If the URL is guaranteed to be valid it can be unwrapped (!) otherwise use optical bindings (if let)
Swift- 5 Easy way
var fileDownloadedURL = URL(string: "")
Declare url in this way
var url: URL = NSURL() as URL

urlNode.objectForKeyedSubscript("href") as? String - Swift 2.3 / Swift 3 error

My code crawls up an HTML page, searches for tags, reads a table on the website and populates a tableView. This worked like a charm in Swift 2.2 but since I've updated Cocoapods, I'm having this error that is refusing to go.
Here is my function:
if let secondColumn = rowElement.childAtIndex(1) as? HTMLElement {
title = secondColumn.textContent
.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
.stringByReplacingOccurrencesOfString("\n", withString: "")
if let urlNode = secondColumn.firstNodeMatchingSelector("a") {
if let urlString = urlNode.objectForKeyedSubscript("href") as? String {
url = NSURL(string: urlString)
if url == nil {
url = NSURL.init(string: "www.mywebsitelink.com")
}
}
}
}
The error is in: urlNode.objectForKeyedSubscript("href") as? String
Error:
Downcast from 'String?' to 'String' only unwraps optionals; did you
mean to use '!'?
This worked fine before and I haven't changed any code at all in this file.
Dependencies:
Alamofire
HTMLReader
Steps taken so far:
Updated code to Swift 2.3 and Swift 3 - doesn't work.
Cleaned code, deleted derived data, etc. - doesn't work.
Tried to flip versions of the dependencies to older versions - doesn't work.
Tried to change optional values i.e. added / removed '!' or '?', tried to change the function by removing 'if let' and just declaring it.
Images of Changes:
Error: conditional binding must have optional type, not string.
Error: unavailable for scripting
Please help.
Resolved it using this syntax:
if let urlString = urlNode["href"] {
}
Not sure if it is correct but getting rid of the text after the '.' seems to be working so far.
It looks to me like your original construct,
urlNode.objectForKeyedSubscript("href")
is of type String? (optional string) not some other type. Thus the as? cast is wrong. You should just use
if let urlString = urlNode.objectForKeyedSubscript("href")? {}

Swift: using plist - error: value of optional type 'String?' not unwrapped

I am very beginner in Swift and I got stuck in this question:
Given a resource named "CrazyInformation.plist" located in the main application directory, first retrieve the path to this resource and assign the string to a constant named plistPath.
Once you have the plistPath, create an instance of NSDictionary containing the contents of the plist.
I am trying this:
import Foundation
// Add your code below
var plistPath = NSBundle.mainBundle().pathForResource("CrazyInformation ",ofType: "plist")
var information = NSArray(contentsOfFile: plistPath)
However, I got this error:
swift_lint.swift:7:43: error: value of optional type 'String?' not unwrapped; did you mean to use '!' or '?'?
var information = NSArray(contentsOfFile: plistPath)
How could I unwrapped this?
The return type of pathForResource is String? i.e. if there is no file of this name in the bundle, it might return a nil.
A good way of writing this code would be
if let plistPath = NSBundle.mainBundle().pathForResource("CrazyInformation", ofType: "plist") {
var information = NSArray(contentsOfFile: plistPath)
}
This will ensure that the code inside the if condition is only executed if pathForResource returns a not-nil value
var plistPath = NSBundle.mainBundle().pathForResource("CrazyInformation ",ofType: "plist")!
See more of optionals here
I think the error is because your using NSArray but the type of CrazzyInformation is a dictionary? I am a beginner as well, but I think that might be it. Try using NSDictionary.

Resources