open text files in same ViewController - ios

I am making app for iPhone in Xcode using Swift i have added multiple buttons on Main.Storyboard and there is one txt file for each Button, Like
class ViewController: UIViewController {
#IBAction func Button1(_ sender: Any) {
opneTextFile(fileName: "example")
}
#IBAction func Button2(_ sender: Any) {
opneTextFile(fileName: "example1")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func opneTextFile(fileName : String) {
if let filepath = Bundle.main.path(forResource: fileName, ofType: "txt") {
do {
let contents = try String(contentsOfFile: filepath)
print(contents)
// Now push second ViewController form here with contents.
if let secondVC = self.storyboard?.instantiateViewController(withIdentifier: "TextViewVC") as? TextViewVC {
secondVC.content = contents
self.navigationController?.pushViewController(secondVC, animated: true)
}
} catch {
// contents could not be loaded
}
} else {
// example.txt not found!
}
}
This Is My TextViewVC and i have create a new ViewController in storyboard with TextView and linked it with TextViewVC file
class TextViewVC: UIViewController {
#IBOutlet var textView: UITextView!
var content : String?
override func viewDidLoad() {
super.viewDidLoad()
textView.text = content
// Do any additional setup after loading the view.
}
Error
but i don't know how to open file when user click on button, it should be something like when user click on button1 the txt1 file should open in ViewController2 and when user click on button2 the txt2 file should open in Same when user click on button1 the txt1 file should open in ViewController as Button1 and the same for rest Buttons..

create a common code for pushing the new viewController.
have created a opneTextFile method in which you just pass a fileName.
func opneTextFile(fileName : String) {
if let filepath = Bundle.main.path(forResource: fileName, ofType: "txt") {
do {
let contents = try String(contentsOfFile: filepath)
print(contents)
// Now push second ViewController form here with contents.
if let secondVC = self.storyboard?.instantiateViewController(withIdentifier: "ViewController2") as? ViewController2 {
secondVC.content = contents
self.navigationController?.pushViewController(secondVC, animated: true)
}
} catch {
// contents could not be loaded
}
} else {
// example.txt not found!
}
}
// action methods
#IBAction func Button1(_ sender: Any) {
opneTextFile(fileName: "example")
}
#IBAction func Button2(_ sender: Any) {
opneTextFile(fileName: "example1")
}
// ViewController2
class ViewController2: UIViewController {
#IBOutlet weak var txt_view: UITextView!
var content : String?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
txt_view.text = content
}
}
NOTE : you can open different files in a same VC.

You should get the text data extracted and show it like you'd show any other string.
let path = Bundle.main.path(forResource: "terms", ofType: "txt")!
let content = try! String(contentsOfFile: path, encoding: .utf8)
note that this is a quick working solution, you should be using try catch block or your app will crash if try! fails.

Related

Why does the second view controller didn´t appear after loading the entry view, but by clicking on a button, he does?

Why does the second view controller didn´t appear after loading the entry view, but by clicking on a button, he does?
Here is my code:
#IBAction func Pressed(_ sender: UIButton) {
var firstName = FirstName.text;
var lastName = LastName.text;
let defaults = UserDefaults.standard;
defaults.set(firstName, forKey: "FN");
defaults.set(lastName, forKey: "LN");
loadNextView()
}
override func viewDidLoad() {
super.viewDidLoad()
self.FirstName.text = "TESTAUSGABE";
let defaults = UserDefaults.standard;
var fn = defaults.object(forKey: "FN")
var ln = defaults.object(forKey: "LN")
if(fn==nil){
self.FirstName.placeholder="Nicht angegeben"
}
else {
self.FirstName.text = fn as? String
loadNextView()
}
if(ln==nil){
self.LastName.placeholder="Nicht angegeben"
}
else{
self.LastName.text = ln as? String
self.Pressed(self.SaveButton);
}
}
func loadNextView(){
let storyboard: UIStoryboard = UIStoryboard(name:"Main", bundle:nil);
let newViewControler = storyboard.instantiateViewController(withIdentifier: "View2") as UIViewController
self.present(newViewControler, animated: true, completion: nil)
}
I want to check the preferences and if they are already set then it should appear automatically another view.
Or is there another method I didn't know?
Prsenting VCs doesn't work inside viewDidLoad as the view hierarchy is not yet complete , You can try to implement viewDidAppear or viewWillAppear
var runOnce = true
//
override func viewDidAppear(_ animated:Bool){
super.viewDidAppear(animated)
if runOnce {
loadNextView() // here read default value
runOnce = false
}
}

How to use UIDocumentInteractionController?

I have created a program that loads PDF files. I want when the user is editing that they can publish the file anywhere in PDF format.
Do I use UIDocumentInteractionController or use UIActivityViewController?
Here is the code:
import UIKit
import PDFKit
#available(iOS 11.0, *)
#available(iOS 11.0, *)
class PDFViewControllerEN: UIViewController {
var document: UIDocumentInteractionController!
override func viewDidLoad() {
super.viewDidLoad()
// retrieve URL to file in main bundle`
}
#IBOutlet var pdfview: UIView!
#IBAction func share(_ sender: UIButton) {
}
#IBAction func doAction2(_ sender: UIBarButtonItem) {
document.presentOptionsMenu(from: view.bounds, in: view, animated: true)
}
override func viewWillAppear(_ animated: Bool) {
//Here you are going to display your PdfController
//PDFController that is seprate class you had created to show pdf file being opened
//i.e
//check which button was being selected
switch ButtonSelected.Tag {
case 0:
var document: UIDocumentInteractionController = {
let pdfView = PDFView(frame: UIScreen.main.bounds)
let url = Bundle.main.url(forResource: "EN1", withExtension: "pdf")
let vc = UIDocumentInteractionController(url: url!)
pdfView.document = PDFDocument(url: url!)
view.addSubview(pdfView)
vc.delegate = self
return vc
}()
// document.presentPreview(animated: true)
break
case 1:
//here control when you selected button with tag 0
//here need to open pdf AR2
//set Frame here all bounds
var document: UIDocumentInteractionController = {
let pdfView = PDFView(frame: UIScreen.main.bounds)
let url = Bundle.main.url(forResource: "EN2", withExtension: "pdf")
let vc = UIDocumentInteractionController(url: url!)
pdfView.document = PDFDocument(url: url!)
view.addSubview(pdfView)
vc.delegate = self
return vc
}()
break
case 2:
//here control when you selected button with tag 0
//here need to open pdf AR2
//set Frame here all bounds
var document: UIDocumentInteractionController = {
let pdfView = PDFView(frame: UIScreen.main.bounds)
let url = Bundle.main.url(forResource: "EN3", withExtension: "pdf")
let vc = UIDocumentInteractionController(url: url!)
pdfView.document = PDFDocument(url: url!)
view.addSubview(pdfView)
vc.delegate = self
return vc
}()
break
default:
//Error Case
print("No tag Value Available")
}
}
}
#available(iOS 11.0, *)
extension PDFViewControllerEN: UIDocumentInteractionControllerDelegate {
func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
return self
}
}
I have tried and explained in detail about UIDocumentInteractionController. Refer this link if you want to check the details.
https://medium.com/if-let-swift-programming/managing-files-in-ios-dfcdfdc1f426
Code
extension ViewController {
/// This function will set all the required properties, and then provide a preview for the document
func share(url: URL) {
documentInteractionController.url = url
documentInteractionController.uti = url.typeIdentifier ?? "public.data, public.content"
documentInteractionController.name = url.localizedName ?? url.lastPathComponent
documentInteractionController.presentPreview(animated: true)
}
/// This function will store your document to some temporary URL and then provide sharing, copying, printing, saving options to the user
func storeAndShare(withURLString: String) {
guard let url = URL(string: withURLString) else { return }
/// START YOUR ACTIVITY INDICATOR HERE
URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data, error == nil else { return }
let tmpURL = FileManager.default.temporaryDirectory
.appendingPathComponent(response?.suggestedFilename ?? "fileName.png")
do {
try data.write(to: tmpURL)
} catch {
print(error)
}
DispatchQueue.main.async {
/// STOP YOUR ACTIVITY INDICATOR HERE
self.share(url: tmpURL)
}
}.resume()
}
}
extension ViewController: UIDocumentInteractionControllerDelegate {
/// If presenting atop a navigation stack, provide the navigation controller in order to animate in a manner consistent with the rest of the platform
func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
guard let navVC = self.navigationController else {
return self
}
return navVC
}
}
extension URL {
var typeIdentifier: String? {
return (try? resourceValues(forKeys: [.typeIdentifierKey]))?.typeIdentifier
}
var localizedName: String? {
return (try? resourceValues(forKeys: [.localizedNameKey]))?.localizedName
}
}
Calling
#IBAction func showOptionsTapped(_ sender: UIButton) {
/// Passing the remote URL of the file, to be stored and then opted with mutliple actions for the user to perform
storeAndShare(withURLString: "https://images5.alphacoders.com/581/581655.jpg")
}
Note
https://www.bignerdranch.com/blog/working-with-the-files-app-in-ios-11/
Before your files can appear in the Files app, you must indicate that your app supports Open in Place and File Sharing Enabled. These options are configured using keys in your Info.plist file.
The first key is UIFileSharingEnabled, which enables iTunes sharing of files in your Documents folder.
The second key is LSSupportsOpeningDocumentsInPlace, which grants the local file provider access to files in your Documents folder.
Add these keys to your Info.plist and set their values to YES.
Using UIDocumentInteractionController is quite easy. You just need to know the url of your file, then you present the menu:
/// Needs to be global, otherwise the controller will be destroyed when the file is handed over to target application
var documentInteractionController: UIDocumentInteractionController!
class MyViewController: UIViewController {
var url: URL
...
#IBAction func share(_ sender: UIBarButtonItem) {
documentInteractionController = UIDocumentInteractionController()
documentInteractionController.url = url
documentInteractionController.uti = url.uti
documentInteractionController.presentOptionsMenu(from: sender, animated: true)
}
}
extension URL {
var uti: String {
return (try? self.resourceValues(forKeys: [.typeIdentifierKey]))?.typeIdentifier ?? "public.data"
}
}
Silly case but might help to someone.
To anyone who can't save files check if your controller is alive. My problem was that my UIDocumentInteractionController was destroyed after it was closed.
Here's how my function looked like:
private func showDocumentInteractionController(url: URL) {
let documentInteractionController = UIDocumentInteractionController(url: url)
documentInteractionController.presentOptionsMenu(from: view.frame, in: view, animated: true)
documentInteractionController.delegate = self
}
The fix is to make sure that UIDocumentInteractionController is alive after it closes:
class ViewController: UIViewController, UIDocumentInteractionControllerDelegate {
private let documentInteractionController = UIDocumentInteractionController()
private func showDocumentInteractionController(url: URL) {
documentInteractionController.url = url
documentInteractionController.presentOptionsMenu(from: view.frame, in: view, animated: true)
documentInteractionController.delegate = self
}
}
This should work which shows a PDF file:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [self] in
guard let path = Bundle.main.url(forResource: "YOUR_PDF_FILE_NAME_WITHOUT_EXTENSION", withExtension: "pdf") else { return }
let documentInteractionController = UIDocumentInteractionController.init(url: path)
documentInteractionController.delegate = self
documentInteractionController.presentPreview(animated: true)
}
}
}
extension ViewController: UIDocumentInteractionControllerDelegate {
func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
return self
}
}

Hide a website button in my tableViewCell

This is code for my custom tableViewCell
#IBOutlet weak var webButton: UIButton!
func update(place:EClass) {
self.place = place
myLabel.text = place.name
myImage.image = nil
myLabel2.text = place.getDescription()
// IF (didClickWebsite) THE SITE DOESN'T EXIST, MAKE INVISIBLE THE BUTTON webButton
if let url = place.photos?.first?.getPhotoURL(maxWidth: maxWidht) {
myImage.af_setImage(withURL: url)
}
}
#IBAction func goToWebSite(_ sender: Any) {
if let place = place, let delegate = delegate {
delegate.didClickWebsite(place: place)
}
}
where I recently added this button #IBOutlet weak var webButton: UIButton!
and this extension is in the VC of my tableView
extension CourseClass2: PlaceCellDelegate {
func didClickWebsite(place: EClass) {
NearbyZone.getZoneDetails(place: place) { (place) in
if let website = place.details?["website"] as? String, let url = URL(string: website) {
let svc = SFSafariViewController.init(url: url)
self.navigationController?.pushViewController(svc, animated: true)
}
}
}
}
what I would like to do is to tell the func update in my custom tableViewCell that if the function didClickWebsite does not produce any results (in this case when the site does not exist) it has to hide the website button, how caI i do this?

Xcode Swift 2 Weather App problems

import UIKit
class ViewController: UIViewController {
#IBOutlet weak var cityNameTextField: UITextField!
#IBOutlet weak var cityNameLabel: UILabel!
#IBOutlet weak var cityTempLabel: UILabel!
#IBAction func getDataButtonClicked(sender: AnyObject) {
getWeatherData("http://api.openweathermap.org/data/2.5/weather?q=\(cityNameTextField.text)&APPID=6de03a1d1554874e7594a89fad719dd0")
}
override func viewDidLoad() {
super.viewDidLoad()
getWeatherData("http://api.openweathermap.org/data/2.5/weather?q=London&APPID=6de03a1d1554874e7594a89fad719dd0")
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getWeatherData(urlString: String) {
let url = NSURL(string: urlString)
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
dispatch_async(dispatch_get_main_queue(), {
self.setLabels(data!)
})
}
task.resume()
}
var jsonData: AnyObject?
func setLabels(weatherData: NSData) {
do {
self.jsonData = try NSJSONSerialization.JSONObjectWithData(weatherData, options: []) as! NSDictionary
} catch {
//error handle here
}
if let name = jsonData!["name"] as? String {
cityTempLabel.text = "\(name)"
}
if let main = jsonData!["main"] as? NSDictionary {
if let temp = main["temp"] as? Double {
cityTempLabel.text = String(format: "%.1f", temp)
}
}
}
};
Yesterday I had the app running and this morning I've just been getting new error messages that won't even allow the code to be compiled. They say 'Missing "Default-568h#2x.png" launch image' and 'Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftcode'. Thanks in advance.
You need to add something to your info.plist file:
It's because the URL link you're trying to get data from is not a secured link, so adding this to you info.plist allows you to access that link. Just go to you info.plist and right-click and select Add Row, then add exactly what you see in the image above.
Also, remove the getWeatherData function from the viewDidLoad method, as you don't need that, as you call it when you press your button.
Also, I've noticed one of your labels isn't set correctly in your setLabels function, as they both try to set the cityTempLabel label, so update the other one to be cityNameLabel.
Build and run and it should all work.

load qr code link in UIwebview swift iOS

hello everybody i have a webview VViewController.swift and
QRCode Scanner QRRViewController.swift how to load the QR Code if its url to a web view direct and not to safari ?
VVCiewcontroller.swift
import UIKit
class VViewController: UIViewController {
#IBOutlet weak var WWebView: UIWebView!
var QRLink:String!
override func viewDidLoad() {
super.viewDidLoad()
var url = NSURL(string: QRLink)
var request = NSURLRequest(URL: url!)
WWebView.loadRequest(request)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func goBack(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
QRRViewController.swift lok like this
this code load the Qr code URL to safari and not to web view
.......
if metadataObj.type == AVMetadataObjectTypeQRCode {
let barCodeObject = videoPreviewLayer?.transformedMetadataObjectForMetadataObject(metadataObj as AVMetadataMachineReadableCodeObject) as! AVMetadataMachineReadableCodeObject
qrCodeFrameView?.frame = barCodeObject.bounds;
if metadataObj.stringValue != nil {
messageLabel.text = metadataObj.stringValue
//if the result is url...
UIApplication.sharedApplication().openURL(NSURL(string: metadataObj.stringValue)!)
}
}
Assuming that you move from the QR view controller to the web views view controller, use the prepare for segue method to pass the link to the next view.
Add this to the QR view controller
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
// Create a variable that you want to send
var QRLink = self.QRLink
// Create a new variable to store the instance of PlayerTableViewController
let destinationVC = segue.destinationViewController as VViewController
destinationVC.QRLink = QRLink
}
Dont forget, you need to also add the variable in the webviews controller to store the QR link.
VVCiewcontroller.swift
import UIKit
class VViewController: UIViewController {
private var QRLink: String
#IBOutlet weak var WWebView: UIWebView!
var QRLink:String!
override func viewDidLoad() {
super.viewDidLoad()
var url = NSURL(string: QRLink)
var request = NSURLRequest(URL: url!)
WWebView.loadRequest(request)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func goBack(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
I assume that you are able to retrieve the string from your qr code reader function,
, also that you have a webview, so try this:
let request = NSURLRequest(URL: "THE URL FROM QRCode")
wvScreen.loadRequest(request)

Resources