This question already has answers here:
Swift - encode URL
(19 answers)
Closed 7 years ago.
This is my code. Error: fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb) I have no idea where;s the problem
res = "https://www.example.com/range.php?arr1=48.15&arr2=48.15&API_KEY=>code"
let url = NSURL(string: res)! // error line
print("url craeted" + res)
return url
The combination => leads to an instruction failure and let's the string not be interpreted as a string.
By the way, I assume res has been defined somewhere else in your code and you want to change "url created" into "url created", later.
You can use an extension to encode your URL
extension String {
func urlEncodedString() -> String {
let urlEncodedString = self.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
return urlEncodedString ?? self
}
}
Related
This question already has answers here:
Swift - encode URL
(19 answers)
Closed 2 years ago.
I have a URL that takes any String like this:
https://test#api.search?query=\(productSearchString)&limit=1
Now my problem is that this works with for example "iphone" but it crashes with "iphone 12".
I tried encoding it like this:
guard let escapedResourceString = resourceString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) else { return }
but this doesn't seem to work in my case because it is returning an incorrect URL that I can not use with my API.
How can I fix this, so the user can type in anything he want but the URL should be created and my API should be able to work with it.
If you need anything more just let me know.
Your parameters needs to be url encoded.
You can use URLComponents to create your URL and pass your parameters as URLQueryItem instances, like that:
let productSearchString = "iphone 12"
var urlComponents = URLComponents(string: "https://test#api.search")
urlComponents?.queryItems = [
URLQueryItem(name: "query", value: productSearchString),
URLQueryItem(name: "limit", value: "1")
]
let url = urlComponents?.url
print(url?.absoluteString ?? "nil") // https://test#api.search?query=iphone%2012&limit=1
This question already has answers here:
Conditional Binding: if let error – Initializer for conditional binding must have Optional type
(8 answers)
Closed 2 years ago.
let saveDocument = Firestore.firestore()
let docId = UserDefaults.standard.object(forKey: "docId") as! String
print(docId)
if let documentRefString = saveDocument.collection("Posts").document(docId) {}
at let documentRefString error message camee out.
Initializer for conditional binding must have Optional type, not 'DocumentReference'
Tell me How to fix this error.
Remove if Let because documentRefString is not optional ... and you cant apply if let on non optionals
saveDocument.collection("Posts").document(docId)
Does not return optional value so change this line to
let documentRefString = saveDocument.collection("Posts").document(docId)
And use documentRefString safely
This question already has answers here:
Unable to remove "Optional" from String
(2 answers)
Closed 2 years ago.
I tried the following code
if let shortURL = shortURL {
var url = "\(shortURL.absoluteString)"
MUser.sharedInstance.setMobileReferralId(url)
self.referralLink.text = url self.copyToClipboard()
}
For the url variable, I get the output Optional("Test"). How do I remove the "Optional" part?
The reason looks like absoluteString is optional so you can provide a default value or using if let to assign its value to url, like below
if let url = shortURL.absoluteString {
print(url)
}
or provide some default blank value like
var url = shortURL.absoluteString ?? ""
print(url)
To remove the Optional part, you only need to unwrap optional right. example:
if let shortURL = shortURL,
let url = shortURL.absoluteString {
print(url)
}
This question already has answers here:
stringByAppendingPathComponent is unavailable
(11 answers)
Closed 5 years ago.
I just converted my project to Swift 3 and I got an error to directory.path row:
Error: Value of type 'String' has no member 'stringByAppendingPathComponent'.
I've already tried let realmPath = (directory as NSString).stringByAppendingPathComponent instead, I have got the following error:
Cannot convert value of type 'URL' to type 'NSString' in coercion.
override func awake(withContext context: Any?) {
super.awake(withContext: context)
let directory: URL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.RazvanJulian.app")!
let realmPath = directory.path.stringByAppendingPathComponent("db.realm") /* ERROR */
RLMRealm.setDefaultRealmPath(realmPath)
realmToken = RLMRealm.default().addNotificationBlock { note, realm in
self.reloadTableData()
}
reloadTableData()
}
Please check it and let me know.
Thank you in advance!
stringByAppendingPathComponent became appendingPathComponent in Swift 3. Try this:
directory.appendingPathComponent("component")
This question already has answers here:
How is optional binding used in swift?
(9 answers)
Closed 6 years ago.
I am working on a project which uses both swift an objective c. The team member before me have written this code in objective C ,which I am not familiar with. There is problem that most of the part involving storing and retrieving value from Sqlite is in obj C. This has been done in a common class to avoid Code redemption. However if i use swift to retrieve value through that obj C file a problem occur. If there is no value in that specified row it return "null".
Update: Checked for optional binding as said by Antony Raphel
Even if i check for nil directly before converting to 'as? String' the same error persist. I came to know that there is no equivalent of "null" in swift. Is there any hack to the value is empty (null) in swift?
Just replace your
var prevNotifCount = self.cmmn.getPreviousNotificationCount() as? String
and use
guard let prevNotifCount = self.cmmn.getPreviousNotificationCount() else{
print("No previous notification value")
return
}
no need to check for nil, if it will fail , else block will be executed
if let prevNotifCount = self.cmmn.getPreviousNotificationCount() as? String
{
self.cmmn.saveInDatabase("19", phoneNumber: "0", otp: "0")
print(self.cmmn.getPreviousNotificationCount())
}
else
{
print("No previous notification value")
}
This is standard Swift approach called optional binding. You safely unwrap an optional and if it is not nil assign it to a local variable
Try by adding if let to check nil condition like this:-
if let NotifCount = self.cmmn,getPreviousNotificationCount() as? String
{
prevNotifCount = NotifCount
}
Please try this, Hope it helps!
Use if let statement.
if let preNotifCount = self.cmmn.getPreviousNotofication {
//business logic
}
Now business logic would only be executed if preNotifCount is not nil.