SWRevealViewController nil error - swift3

I am using SWRevealViewController
When i was click on BackButton getting this error
fatal error: unexpectedly found nil while unwrapping an Optional value
my code
let nesne:SWRevealViewController = self.revealViewController()//the error here
let mainStroyBoard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let desController = mainStroyBoard.instantiateViewController(withIdentifier: "MessageViewController") as! MessageViewController
let newFrontViewController = UINavigationController.init(rootViewController:desController)
nesne.pushFrontViewController(newFrontViewController, animated: true)

solution
let sw = storyboard?.instantiateViewController(withIdentifier: "SWRevealViewController") as! SWRevealViewController
self.view.window?.rootViewController = sw
let mainStroyBoard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let desController = mainStroyBoard.instantiateViewController(withIdentifier: "MessageViewController") as! MessageViewController
let newFrontViewController = UINavigationController.init(rootViewController:desController)
sw.pushFrontViewController(newFrontViewController, animated: true)

Related

Convert HTML text to displayable text in swiftUI [duplicate]

I was wondering how can HTML tags be stripped out of JSON from a web url. Do I have to use NSString of something similar.
So I am looking to strip out the html tags that are in the summary value. I looked around abit and it says NSString can be used but I was not sure if that was something that could be implemented into Swift 3. Any Help would be appreciated.
My code:
import UIKit
import Alamofire
struct postinput {
let mainImage : UIImage!
let name : String!
let author : String!
let summary : String!
}
class TableViewController: UITableViewController {
var postsinput = [postinput]()
var mainURL = "https://www.example.com/api"
typealias JSONstandard = [String : AnyObject]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
callAlamo(url: mainURL)
}
func callAlamo(url : String){
Alamofire.request(url).responseJSON(completionHandler: {
response in
self.parseData(JSONData: response.data!)
})
}
func parseData(JSONData : Data) {
do {
var readableJSON = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers) as! JSONstandard
// print(readableJSON)
if let posts = readableJSON["posts"] as? [JSONstandard] {
for post in posts {
let title = post["title"] as! String
let author = post["author"] as! String
guard let dic = post["summary"] as? [String: Any], let summary = dic["value"] as? String else {
return
}
print(author)
if let imageUrl = post["image"] as? String {
let mainImageURL = URL(string: imageUrl )
let mainImageData = NSData(contentsOf: mainImageURL!)
let mainImage = UIImage(data: mainImageData as! Data)
postsinput.append(postinput.init(mainImage: mainImage, name: title, author: author, summary: summary))
}
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
catch {
print(error)
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return postsinput.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
// cell?.textLabel?.text = titles[indexPath.row]
let mainImageView = cell?.viewWithTag(2) as! UIImageView
mainImageView.image = postsinput[indexPath.row].mainImage
//(cell?.viewWithTag(2) as! UIImageView).image = postsinput[indexPath.row].mainImage
let mainLabel = cell?.viewWithTag(1) as! UILabel
mainLabel.text = postsinput[indexPath.row].name
mainLabel.font = UIFont(name: "Helvetica", size:14)
let autLabel = cell?.viewWithTag(3) as! UILabel
autLabel.text = postsinput[indexPath.row].author
autLabel.font = UIFont(name: "Helvetica", size:12)
let sumLabel = cell?.viewWithTag(4) as! UILabel
sumLabel.text = postsinput[indexPath.row].summary
sumLabel.font = UIFont(name: "Helvetica", size:12)
//(cell?.viewWithTag(3) as! UILabel).text = postsinput[indexPath.row].author
return cell!
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
You can use this code for stripping html tags
From your previous question
guard let dic = post["summary"] as? [String: Any], let summary = dic["value"] as? String else {
return
}
let str = summary.replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression, range: nil)
print(str)
Edit
I have checked it and it is working
let summary = "<p>Latin text here</p>"
let str = summary.replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression, range: nil)
print(str)
Latin text here

Setting Container Controller (Root View Controller) as Delegate for View Controllers in UITabBarController

I'm trying to set a Container Controller (Root View Controller) as the delegate for a Nav Bar Item for a View Controller in a Tab Bar Controller and cannot figure out how to do this without using:
let rootViewController = UIApplication.shared.keyWindow?.rootViewController
This code works as I'd like it to:
let rootViewController = UIApplication.shared.keyWindow?.rootViewController
guard let doghouseViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "DoghouseVC") as? DoghouseViewController else { return }
doghouseViewController.delegate = rootViewController as? DoghouseViewControllerDelegate
let nav1 = UINavigationController(rootViewController: doghouseViewController)
guard let statsViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "StatsVC") as? StatsViewController else { return }
statsViewController.delegate = rootViewController as? StatsViewControllerDelegate
let nav2 = UINavigationController(rootViewController: statsViewController)
dailyWrapUpViewController = DailyWrapUpViewController()
guard let calendarViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "CalendarVC") as? CalendarViewController else { return }
calendarViewController.delegate = rootViewController as? CalendarViewControllerDelegate
let nav3 = UINavigationController(rootViewController: calendarViewController)
guard let settingsViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SettingsVC") as? SettingsViewController else { return }
settingsViewController.delegate = rootViewController as? SettingsViewControllerDelegate
let nav4 = UINavigationController(rootViewController: settingsViewController)
doghouseViewController.tabBarItem = UITabBarItem(title: "Doghouse", image: UIImage(named: "doghouse"), tag: 0)
statsViewController.tabBarItem = UITabBarItem(title: "Stats", image: UIImage(named: "stats"), tag: 1)
// Custom Doggy Bag Button
let controller2 = UIViewController()
calendarViewController.tabBarItem = UITabBarItem(title: "Calendar", image: UIImage(named: "calendar"), tag: 3)
settingsViewController.tabBarItem = UITabBarItem(title: "More", image: UIImage(named: "more"), tag: 4)
viewControllers = [nav1, nav2, controller2, nav3, nav4]
// Use the view controller reference to select the second tab
selectedViewController = nav1
But, 'keyWindow' was deprecated in iOS 13.0 and if I try to change it using the following as an example, the delegate functionality doesn't work (button gets pushed, but Container Controller instance does not receive):
let rootViewController = UIApplication.shared.windows.first!.rootViewController as! ContainerController
For more context, the Container Controller (Root View Controller) is a side menu that slides out on the tap of a NavBar Item within the TabBarController.
How do I solve this?
Figured it out:
let sceneDelegate = UIApplication.shared.connectedScenes.first!.delegate as! SceneDelegate
guard let doghouseViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "DoghouseVC") as? DoghouseViewController else { return }
doghouseViewController.delegate = sceneDelegate.window!.rootViewController as? DoghouseViewControllerDelegate
let nav1 = UINavigationController(rootViewController: doghouseViewController)
guard let statsViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "StatsVC") as? StatsViewController else { return }
statsViewController.delegate = sceneDelegate.window!.rootViewController as? StatsViewControllerDelegate
let nav2 = UINavigationController(rootViewController: statsViewController)
dailyWrapUpViewController = DailyWrapUpViewController()
guard let calendarViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "CalendarVC") as? CalendarViewController else { return }
calendarViewController.delegate = sceneDelegate.window!.rootViewController as? CalendarViewControllerDelegate
let nav3 = UINavigationController(rootViewController: calendarViewController)
guard let settingsViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SettingsVC") as? SettingsViewController else { return }
settingsViewController.delegate = sceneDelegate.window!.rootViewController as? SettingsViewControllerDelegate
let nav4 = UINavigationController(rootViewController: settingsViewController)
doghouseViewController.tabBarItem = UITabBarItem(title: "Doghouse", image: UIImage(named: "doghouse"), tag: 0)
statsViewController.tabBarItem = UITabBarItem(title: "Stats", image: UIImage(named: "stats"), tag: 1)
// Custom Doggy Bag Button
let controller2 = UIViewController()
calendarViewController.tabBarItem = UITabBarItem(title: "Calendar", image: UIImage(named: "calendar"), tag: 3)
settingsViewController.tabBarItem = UITabBarItem(title: "More", image: UIImage(named: "more"), tag: 4)
viewControllers = [nav1, nav2, controller2, nav3, nav4]
// Use the view controller reference to select the second tab
selectedViewController = nav1

Presenting view controllers on detached view controllers is discouraged (with SWRevealViewController)

I am changing the RootViewController of SwRevealViewController
My code:
let next = self.storyboard?.instantiateViewController(withIdentifier: "SWRevealViewController") as! SWRevealViewController
next.loadView()
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = mainStoryboard.instantiateViewController(withIdentifier: "MessageViewController") as! MessageViewController
UIApplication.shared.keyWindow?.rootViewController = viewController;
self.present(next, animated: true, completion: nil)
But I get this error:
>Presenting view controllers on detached view controllers is discouraged <ios.MesajDetayViewController: 0x7f8718d646f0>.
How to solve?
solution
let sw = storyboard?.instantiateViewController(withIdentifier: "SWRevealViewController") as! SWRevealViewController
self.view.window?.rootViewController = sw
let mainStroyBoard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let desController = mainStroyBoard.instantiateViewController(withIdentifier: "MessageViewController") as! MessageViewController
let newFrontViewController = UINavigationController.init(rootViewController:desController)
sw.pushFrontViewController(newFrontViewController, animated: true)
if you want to change SWRevealViewContoller front view controller, you should use
let newFronViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "YourID") as! YourClass
self.revealViewController().setFront(newFronViewController, animated: false)
I can update my answer depending on where you would like to call this.

Tab Bar not showing when push notifications clicked and goes to a Specific ViewController in Swift 3.0?

I am receiving Push Notifications when i click on Notification i want to go to a particular ViewController opens when click i click on SlideMenu didSelectRow. I tried many SO links but below code i am able to go to a particular ViewController but problem is tabBar it not showing.
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
let mainstoryboard = UIStoryboard(name: "Main", bundle: nil)
let ringingVC = mainstoryboard.instantiateViewController(withIdentifier: "RaffleResultViewController") as? RaffleResultViewController
window?.rootViewController = ringingVC
}
let mainstoryboard = UIStoryboard(name: "Main", bundle: nil)
let ringingVC = mainstoryboard.instantiateViewController(withIdentifier: "RaffleResultViewController") as? RaffleResultViewController
let selectedVC = window.rootViewController
if let nav = selectedVC as? UINavigationController{
nav.pushViewController(ringingVC, animated: true)
}else{
selectedVC.present(ringingVC, animated: true, completion: nil)
}
// USE this

Updating an URLSession to swift 3 throwing error

I updated my code to Swift 3 and most of it converted over fine except from the URLSession and I cant find a solution to this error:
Cannot invoke 'dataTask' with an argument list of type '(with: NSMutableURLRequest, completionHandler: (Data?, URLResponse?, NSError?) -> Void)'
This is my code:
let post:NSString = "username=\(username)&userPassword=\(password)&userEmail=\(email)" as NSString
let url:URL = URL(string: "http://ec2-54-201-55-114.us-west-2.compute.amazonaws.com/wickizerApp/ApplicationDB/scripts/registerUser.php")!
let request = NSMutableURLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = post.data(using: String.Encoding.utf8.rawValue)
URLSession.shared.dataTask(with: request, completionHandler: { (data:Data?, response:URLResponse?, error:NSError?) -> Void in
DispatchQueue.main.async
{
if error != nil {
self.displayAlertMessage(error!.localizedDescription)
return
}
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
let status = parseJSON["status"] as? String
if( status! == "200")
{
let myAlert = UIAlertController(title: "Alert", message: "Registration successful", preferredStyle: UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default){(action) in
self.dismiss(animated: true, completion: nil)
}
myAlert.addAction(okAction);
self.present(myAlert, animated: true, completion: nil)
} else {
let errorMessage = parseJSON["message"] as? String
if(errorMessage != nil)
{
self.displayAlertMessage(errorMessage!)
}
}
}
} catch{
print(error)
}
}
}).resume()
Is there a different way to do requests in swift 3 or did they just change the way to do them?
The compiler wants URLRequest and Error
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = post.data(using: .utf8)
URLSession.shared.dataTask(with: request, completionHandler: { (data:Data?, response:URLResponse?, error:Error?) -> Void in
})
or still shorter
URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in
})
or still shorter
URLSession.shared.dataTask(with: request) { (data, response, error) in
}