Im having a big trouble with URl
I want to use url for almofire , but unforutnately it always return nil
or ortherwise , this solutuin return valid URL but with weird $$*%&$( in front of https:// an resulting to always got nil response
let req = "​https://api-staging.xx.oo/v1/s-locations/"
guard let percentReq = req.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed ) else { return nil }
let urlReq = URL(string: percentReq)!
// work , url got , but fetch nothing
let urlReq = URL(string: req)!
// error FATAL
Honestly, looks like you managed to get some trash into the string by copy-pasting, I'm assuming it's encoding or something. This code from below works just fine:
let test = "https://api-staging.xx.oo/v1/s-locations/"
let url = URL(string: test)
Related
I am trying to add a suggestion/feedback section in my app. It's supposed to open a mail app with pre-populated text for the subject, body, and email address. It's working fine except the subject and body show the percent-encoding for space. I have searched a lot and it seems like an iOS 15 issue but I am not sure. This is my code:
private func createEmailUrl(to: String, subject: String, body: String) -> URL? {
let subjectEncoded = subject.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
let bodyEncoded = body.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
let gmailUrl = URL(string: "googlegmail://co?to=\(to)&subject=\(subjectEncoded)&body=\(bodyEncoded)")
let outlookUrl = URL(string: "ms-outlook://compose?to=\(to)&subject=\(subjectEncoded)")
let yahooMail = URL(string: "ymail://mail/compose?to=\(to)&subject=\(subjectEncoded)&body=\(bodyEncoded)")
let sparkUrl = URL(string: "readdle-spark://compose?recipient=\(to)&subject=\(subjectEncoded)&body=\(bodyEncoded)")
let defaultUrl = URL(string: "mailto:\(to)?subject=\(subjectEncoded)&body=\(bodyEncoded)")
if let gmailUrl = gmailUrl, UIApplication.shared.canOpenURL(gmailUrl) {
return gmailUrl
} else if let outlookUrl = outlookUrl, UIApplication.shared.canOpenURL(outlookUrl) {
return outlookUrl
} else if let yahooMail = yahooMail, UIApplication.shared.canOpenURL(yahooMail) {
return yahooMail
} else if let sparkUrl = sparkUrl, UIApplication.shared.canOpenURL(sparkUrl) {
return sparkUrl
}
return defaultUrl
}
And this is how I am calling the API
UIApplication.shared.open(url)
The Gmail app shows the subject as:
Reg:%2520Suggestions/Feedback%2520About%2520iOS%2520App
It wasn't an issue at all. I was sending an already encoded string and it was encoding % to %25. Hence all my encoded special characters were converted into %25__.
My bad. I must read the code properly before copy-pasting.
When passing the valid url of the string with the init the URL(string: urlString) returns nil. How to fix? When I enter a value from one word (for example, Moscow) everything works, when a city from two words is entered, I separate the request using split(separator: " ") and connect using .joined(separator: "%20") and get the city divided by %20 and return nil. How can this problem be solved?
enter image description here
enter image description here
You need to do addingPercentEncoding see my extension for that
extension String {
var url: URL? {
guard !isEmpty else { return nil }
if let url = URL(string: self) {
return url
} else if let urlEscapedString = addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
let escapedURL = URL(string: urlEscapedString) {
return escapedURL
}
return nil
}
}
Use the apiKey after encoding it:
let encodedKey = key.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
I have Medicine struct that holds image_origin URL of image I want to download and set to the ImageView.
For downloading/caching purposes I'm using Kingfisher framework.
let m = medicines[indexPath.row]
cell.medicineImage.kf.setImage(with: URL(string: m.value(forKeyPath: "image_origin") as! String)!)
cell.medicineName.text = m.value(forKeyPath: "i_name") as? String
In the code above m is an NSManagedObject of CoreData. I try to get image URI from the CoreData and set it to the ImageView, but every time at the line 2 I get the following error message: Unexpectedly found nil while unwrapping an Optional value
I have tried changing variables and Optinal types, tried to hardcode URI but without success.
What am I doing wrong?
P.S. Im using Swift4
Just unwrap safely to fix the crash and check your database if you are not getting the urlString properly,
if let urlString = m.value(forKeyPath: "image_origin") as? String {
print(urlString)
guard let url = URL(string: urlString) else { return }
cell.medicineImage.kf.setImage(with: url)
}
There might be a problem with image_origin key that I may have value as string or may not have. So, just need to confirm the value and use it
let m = medicines[indexPath.row]
cell.medicineName.text = m.value(forKeyPath: "i_name") as? String
guard let urlPath = m.value(forKeyPath: "image_origin") as? String, let url = URL(string: urlPath) else { return }
cell.medicineImage.kf.setImage(with: url)
Here is my situation: i'm calling file locally on my ios application ( Running in Swift).
If the file is a jpg, one action happen, if the file is a mp4, another action happen.
For this i'musing this code:
let urlString = "\(posts[selectedIndexPath].link)"
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let fileName = urlString as NSString;
let filePath="\(documentsPath)/\(fileName.lastPathComponent)";
let fileURL = NSURL.init(fileURLWithPath: filePath)
let request = NSURLRequest.init(url: fileURL as URL)
/* END DOWNLOAD + READ LOCALY */
if (fileURL.pathExtension?.hasPrefix("jpg"))! {
Swift.print("THIS IS A JPG")
}
else if (fileURL.pathExtension == "mp4") {
Swift.print("THIS IS A MP4")
}
This works perfectly.
What i need to do now is instead of calling th eifle locally, to calling it form an URL.
I read my file from an url by:
videoVRView.load(from: URL(string: "\(posts[selectedIndexPath].link)")
Which work.
But from that, the action is not working, i've try the following:
if ((from: URL(string: "\(posts[selectedIndexPath].link)").hasPrefix("jpg"))! {
Swift.print("THIS IS A JPG")
}
else if ((from: URL(string: "\(posts[selectedIndexPath].link)") == "mp4") {
Swift.print("THIS IS A MP4")
}
Without any success !!
Does anybody know how is this achievable ?
Thanks a lot =)
-- EDIT --
What im trying to do is th efollowing to resume:
at th emoment i call image locally via:
imageVRView.load(UIImage(named: "\(documentsPath)/\(fileName.lastPathComponent)" ),
of: GVRPanoramaImageType.stereoOverUnder)
I try instead to use:
imageVRView.load(UIImage(named: "\(posts[selectedIndexPath].link)" ),
of: GVRPanoramaImageType.stereoOverUnder)
Without success . . . . I need to call the image via this method ... any idea ?
Thanks a lot !
You can make a URL request for the url header using the httpMethod HEAD to check your url mime type without the need to download the data first:
let link = "https://www.dropbox.com/s/sk46eyglvijlrec/horse.jpg?dl=1"
let url = URL(string: link)!
var request = URLRequest(url: url)
request.httpMethod = "HEAD"
URLSession.shared.dataTask(with: request) { _ , response , _ in
guard let response = response, (response as? HTTPURLResponse)?.statusCode == 200 else { return }
DispatchQueue.main.async() {
print("mimeType", response.mimeType ?? "nil") // image/jpeg
print("suggestedFilename:", response.suggestedFilename ?? "no suggestedFilename") // horse.jpg
print("expectedContentLength:", response.expectedContentLength ?? "nil") // 352614
print("textEncodingName:", response.textEncodingName ?? "nil")
print("url:", response.url ?? "nil") // "https://dl.dropboxusercontent.com/content_link/RNrhGtvroTLU1Gww7eQo1N1ePRiix68zsqZJ1xWPjKm3pmOUNQwNVntbPuFG4jZ8/file?dl=1"
}
}.resume()
Getting an "unexpected found nil" error, but when checking the value - its there:
override func viewDidLoad() {
super.viewDidLoad()
if whichLink == "official link" {
let urlStr = videoGame.offLink!
let url = NSURL(string: urlStr)!
let request = NSURLRequest(URL: url)
webView.loadRequest(request)
}
else if whichLink == "moby game link" {
print("yo yo yo, value is here! \(videoGame.mgLink) ")
let urlStr1 = videoGame.mgLink!
let url1 = NSURL(string: urlStr1)!
let request = NSURLRequest(URL: url1)
webView.loadRequest(request)
}
}
I'm suspecting an error in storyboard... but can't locate anything.
Did anyone has a clue what can be wrong?
The full project can be found # https://github.com/flostik2008/Favorite-Games
Your URL string is incorrectly formatted with the space at the end, so the NSURL initialization is returning nil.
You should URL encode all raw strings before trying to create an NSURL:
let urlStr1 = videoGame.mgLink!.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())! should work