I don't want to write the link " https://stackoverflow.com/questions/ask" as shown in this line. I want url to receive the last copied URL from clipboard, what should I add?
let url = URL(string: "https://stackoverflow.com/questions/ask")
Copy
let url = URL(string: "https://stackoverflow.com/questions/ask")
UIPasteboard.general.string = url
Paste
if let url = UIPasteboard.general.string {
url = url
}
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.
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)
I am calling API wih 'Alamofire'. In my response I get one weblink. I store that weblink in to one variable. Now I want to store that weblink into the local database. so I use 'userdefaults'. But when I retrive that weblink into the other 'viewcontroller' at that time my weblink changed and web page didnot open.
let weblink = datastring["Web_Link"] as! String
UserDefaults.standard.set(weblink, forKey: "Link")
for these I use this
UserDefaults.standard.set(url: URL?, forKey: String)
and in another 'viewcontroller'
let url = UserDefaults.standard.url(forKey: "Link")
for these I used
let url = UserDefaults.standard.url(forKey: String)
and my other code is
let request = URLRequest.init(url: url!)
self.webview.load(request)
my url example is "https://example.com/"
but when I retrive at that time url is
'https:/example.com'
so my webpage cannot open. I am using wkwebview.
You store the url as string so retrieve it like this.
let url = UserDefaults.standard.string(forKey: "Link")
It looks like you are storing String value in user defaults and trying to get URL from UserDefaults. So Please try as like below.
let weblink = datastring["Web_Link"] as! String
if let url = URL(string: weblink){
UserDefaults.standard.set(url, forKey: "Link")
}
I have generated a URL with the following function below. I would like to save this to the local folder for use later on. However, when I save it to the local folder, and then retrieve it, the URL is truncated. Please can someone advise on how I would be able to save and extract the full URL?
func createPhotoURL() -> URL {
let fileName = "tempImage_wb.jpg"
let documentsDirectories = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentDirectory = documentsDirectories.first!
let pdfPageURL = documentDirectory.appendingPathComponent("\(fileName)")
return pdfPageURL
}
When I call the function I get the full length URL:
let imageURL = createPhotoURL() // CORRECT URL FOR FILE UPLAOD
print("imageURL: \(imageURL)")
Console:
file:///var/mobile/Containers/Data/Application/CDDE2FED-5AAB-4960-9ACF-33E7B42D05AE/Documents/tempImage_wb.jpg
Save above URL to local folder and the retrieve it:
UserDefaults.standard.set(imageURL, forKey: "URL_IMAGE")
guard let retrievedURL = UserDefaults.standard.string(forKey: "URL_IMAGE") else{return}
print("retrievedURL: \(retrievedURL)")
Console:
retrievedURL: ~/Documents/tempImage_wb.jpg
To answer your question, use UserDefaults.standard.url instead of UserDefaults.standard.string
guard let retrievedURL = UserDefaults.standard.url(forKey: "URL_IMAGE") else{return}
But this will work only if you save the path and retrieve it in the same session. If you use the above code and run the app multiple times, you will get non-truncated urls (like you want). But if you check it properly you can see you are actually getting different urls in different sessions.
So you shouldn't save it as a URL, instead you should save it as string. For that you can use absoluteString property of URL
let imageURL = createPhotoURL()
print("imageURL: \(imageURL)")
UserDefaults.standard.set(imageURL.absoluteString, forKey: "URL_IMAGE")
And to retrieve, you will first retrieve the saved string from UserDefaults and then convert that into a URL
if let urlString = UserDefaults.standard.string(forKey: "URL_IMAGE"),
let retrievedURL = URL(string: urlString) {
print("retrievedURL: \(retrievedURL)")
}
I want to show a local image from CachesDirectory in a webview.
The webview can't load it. The bundle doesn't contain the image!
I download the image from the server but I have a local HTML file with the image tag. How can I do it?
My path where the image exists:
/Users/adambella/Library/Developer/CoreSimulator/Devices/BFA8C179-EBC5-49A7-95F3-1ABA202F44AD/data/Containers/Data/Application/746BE86B-33D7-4A6F-8C4C-0E4453FE374C/Library/Caches/swift.imageloader.diskcached/
Anybody could give me a short example?
I downloaded it with ImageLoader.
Path with Name:
var path: String {
let cacheDirectory = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)[0]
let directoryName = "swift.imageloader.diskcached"
return cacheDirectory + "/" + directoryName
}
let filePath = NSBundle.mainBundle().pathForResource("example", ofType: "html",inDirectory: "Directory")
let urlToFile = NSURL(fileURLWithPath: filePath!)
let request = NSURLRequest(URL: urlToFile, cachePolicy: .ReturnCacheDataElseLoad, timeoutInterval: 10.0)
and in webViewDidFinishLoad method:
webview2.stringByEvaluatingJavaScriptFromString("testImage('\(path)')")
function in html file:
function testImage(url) {
var mapDiv = document.getElementById("map");
mapDiv.innerHTML = "<img src=file://" + url + "/>";
}
This is Swift 4.2 code.
base URL in you can set Image URL
web.loadRequest(URLRequest.init(url: baseURL!))
If you have any query please comment