#IBAction func download(_ sender: Any) {
if let url = URL(string: "\(imgURL)") {
UIApplication.shared.openURL(url as URL)
}
print(imgURL)
}
The url wont open if i press the button. The consol says the right url: https://scontent-ams3-1.cdninstagram.com/t51.2885-19/18514045_212505245924563_1350282415863496704_a.jpg but the url wont open. Please help! Thanks
let urlstr = "\(profile_pic_url_hd)"
if var comps = URLComponents(string: urlstr) {
var path = comps.path
var pathComps = path.components(separatedBy: "/")
pathComps.remove(at: 2) // this removes the s320x320
path = pathComps.joined(separator: "/")
comps.path = path
if let newStr = comps.string {
print(newStr)
self.imgURL = "\(newStr)"
}
}
Related
I have already copy the file absolute path and paste in simulator browser, the image can be opened. But the fileExists is fail, i dont know why..... Can anyone help
let defaultImage = "302C3FA1-E4E1-4CD8-B6DF-2FF4E4E24C11.jpeg"
loadImage(at: defaultImage)
func fileExists(at path: String) -> Bool {
return FileManager.default.fileExists(atPath: path)
}
func loadImage(at path: String) -> UIImage? {
let tempPath = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
let imagePath = "\(tempPath)\(path.trimmingCharacters(in: .whitespacesAndNewlines))"
guard fileExists(at: imagePath) else { return nil }
guard let image = UIImage(contentsOfFile: imagePath) else { return nil }
return image
}
You need split filename and extension filename.
If you use main bundle. you can follow this code
let stringPath = Bundle.main.path(forResource: "your_filename", ofType: "txt")
let urlPath = Bundle.main.url(forResource: "your_filename", withExtension: "txt")
or you can use my code.
func readConfigFromBundle(fileExtension: String) -> TCBConfigure? {
let bundle = Bundle.main
if let resPath = bundle.resourcePath {
do {
let dirContents = try FileManager.default.contentsOfDirectory(atPath: resPath)
let filteredFiles = dirContents.filter { $0.contains(fileExtension) }
for fileName in filteredFiles {
let sourceURL = bundle.bundleURL.appendingPathComponent(fileName)
let data: NSData? = NSData.init(contentsOf: sourceURL)
if let fileData = data {
// implement your logic
}
}
} catch {
// implement when error
}
}
return nil
}
I wish to open app with the latest url viewd on a webview ios app.
Tryied this inside viewdidload()
var hasHistoryUrl = false
WebView.evaluateJavaScript("window.location.href") {
(result,error)->Void in if (result != nil){
hasHistoryUrl=true
}
}
if (hasHistoryUrl){
// let url = URL(string: historyUrl)
} else {
let url = URL(string: "https://www.url.com/")
let request = URLRequest(url: url!)
loadReq(request: request);
}
Not working on true device, on emulators allways opens with a clear cache.
When you open your app, all variable initialise and your previous data will be gone. So you need to save latest visited url in userdefaults as string like-
let url: String = "abcd.com"
UserDefaults.standard.set(url, forKey: "MyUrl")
And fetch url from userdefaults when you open the app as -
if let urlString = UserDefaults.string(forKey: ""MyUrl"") {
// Do stuff
}
In your code, insert it as-
WebView.evaluateJavaScript("window.location.href") {
(result,error)->Void in if (result != nil){
UserDefaults.standard.set(yourURL, forKey: "MyUrl")
}
}
if let urlString = UserDefaults.string(forKey: ""MyUrl"") {
// Do stuff
} else {
let url = URL(string: "https://www.url.com/")
let request = URLRequest(url: url!)
loadReq(request: request);
}
I am integrating sharing options from my app to Snapchat.
I have a dynamic URL obtained in an object and clicking the Snapchat's share button directly opens the app if Snapchat is there on the device and show the text with the link. I am using the below code to share which gives an error on Snapchat. Below is my Code.
func shareTextOnSnapchat(obj:VideoData) {
let shaUrl = URL(string: obj.share_url ?? "")
if let myURL:URL = shaUrl{
let promoText = "Check out this great new video from \(obj.name ?? ""), I found on talent app"
let shareString = "snapchat://text=\(promoText)&url=\(myURL)"
let escapedShareString = shareString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
let url = URL(string: escapedShareString)
UIApplication.shared.openURL(url!)
}
}
I have used this to post video to snapchat. You have option to either post text or a video.
Pod used
pod 'SnapSDK', :subspecs => ['SCSDKCreativeKit']
import SCSDKCreativeKit
var scInstalled = false
override func viewDidLoad() {
super.viewDidLoad()
scInstalled = schemeAvailable(scheme: "snapchat://")
}
func ShowSnapchat(){
if scInstalled {
//shareTextOnSnapchat(obj:videoObj ?? VideoData())
shareFileOnSnapchat(obj:videoObj ?? VideoData())
}else{
downloadSharingAppAlert(appName:"Snapchat")
}
}
func shareTextOnSnapchat(obj:VideoData) {
let shaUrl = URL(string: obj.share_url ?? "")
if let myURL:URL = shaUrl{
let originalString = "\(myURL)"
let escapedString = originalString.addingPercentEncoding(withAllowedCharacters:CharacterSet.urlQueryAllowed)
//let url = URL(string: "snapchat://snap?text=\(escapedString!)")
let url = URL(string: "https://www.snapchat.com/send?text=\(escapedString!)")
if UIApplication.shared.canOpenURL(url! as URL)
{
UIApplication.shared.open(url! as URL, options: [:], completionHandler: nil)
}
}
}
func shareFileOnSnapchat(obj:VideoData){
//// SHARE VIDEO
LoadingOverlay.shared.showLoaderView(view: self.view)
let shaUrl = URL(string: obj.output_vid ?? "")
if let myURL:URL = shaUrl{
let snapVideo = SCSDKSnapVideo(videoUrl: myURL)
let snapContent = SCSDKVideoSnapContent(snapVideo: snapVideo)
// Send it over to Snapchat
snapAPI.startSending(snapContent) { (error) in
if let error = error {
print(error.localizedDescription)
LoadingOverlay.shared.hideLoaderView()
MyCustomAlert.sharedInstance.ShowAlert(vc: self, myTitle: "", myMessage: StringClass.sharedInstance.lcStr_oopsSomethingWentwrong)
} else {
// success
print("Posted to snapchat")
LoadingOverlay.shared.hideLoaderView()
MyCustomAlert.sharedInstance.ShowAlert(vc: self, myTitle: "", myMessage: StringClass.sharedInstance.lcStr_postedToSnapchat)
}
}
}
}
}
func downloadSharingAppAlert(appName:String){
var appStoreURL = "https://apps.apple.com/in/app/snapchat/id447188370"
//Open Appstore for Download
}
I have this url https://storage.googleapis.com/user_avatars/63/img_-qLgH80SBqNhMRYbDQeccg.jpg
I need only qLgH80SBqNhMRYbDQeccg image name from this link In ui Image
You can use NSURL to safely isolate the filename then use substring to get the part you want.
let s = "https://storage.googleapis.com/user_avatars/63/img_-qLgH80SBqNhMRYbDQeccg.jpg"
Swift 2
if let url = NSURL(string: s),
withoutExt = url.URLByDeletingPathExtension,
name = withoutExt.lastPathComponent {
let result = name.substringFromIndex(name.startIndex.advancedBy(5))
print(result)
}
Swift 3
if let url = URL(string: s),
withoutExt = try? url.deletingPathExtension(),
name = withoutExt.lastPathComponent {
let result = name.substring(from: name.index(name.startIndex, offsetBy: 5))
print(result)
}
Swift 4
if let url = URL(string: s) {
let withoutExt = url.deletingPathExtension()
let name = withoutExt.lastPathComponent
let result = name.substring(from: name.index(name.startIndex, offsetBy: 5))
print(result)
}
Prints:
qLgH80SBqNhMRYbDQeccg
What about something that uses NSURLComponents to break up the URL:
func parseURLForFileName(url:String) ->String?
{
let components = NSURLComponents(string: url)
if let path:NSString = components?.path
{
let filename = path.lastPathComponent
if let range = filename.rangeOfString("_-")
{
return filename.substringFromIndex(range.endIndex)
}
}
return nil
}
You would then call it like this:
let name = parseURLForFileName("https://storage.googleapis.com/user_avatars/63/img_-qLgH80SBqNhMRYbDQeccg.jpg")
print(name)
The code seems to pick up the right variable, but never opens the Instagram App to display that image.
func showOriginWebPage() {
println("showOriginWebPage: \(self.id!)")
if let appURL = NSURL(string: "instagram://media?id=\(self.id)") {
let canOpen = UIApplication.sharedApplication().canOpenURL(appURL)
}
}
// println: showOriginWebPage: 932481051119413840_1563069185
thanks for any pointers.
Here is how i do it
#IBAction func openOnInstagramAction(sender: AnyObject) {
var instagramURL = NSURL(string: "instagram://user?id=" + "1234567890" )
if (UIApplication.sharedApplication().canOpenURL(instagramURL!)) {
UIApplication.sharedApplication().openURL(instagramURL!)
}else {
println("Instagram not installed")
}
}