I am only coding in two features. MailComposer and WebView. But when I run my app and go to the email interface tab it crashes "fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)". When I go to the tab that displays the webview, it works fine. The Webview.loadRequest(request) is messing something up with the mail coding. But I don't know where I can put it to make both features work.
If anyone has any clue how to fix this, please let me know. Thanks.
Here is the coding for the View.Controller.Swift file...
import UIKit
import MessageUI
class ViewController: UIViewController, MFMailComposeViewControllerDelegate {
#IBOutlet weak var Webview: UIWebView!
#IBOutlet weak var Subject: UITextField!
#IBOutlet weak var Body: UITextView!
var URLPath = "http://google.com"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
loadAddressURL()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func SendEmail(sender: AnyObject) {
var SubjectText = "Inquiry:"
SubjectText += Subject.text
var MessageBody = Body
var toRecipients = ["phillip.lebsack1#gmail.com"]
var mc: MFMailComposeViewController = MFMailComposeViewController()
mc.mailComposeDelegate = self
mc.setSubject(SubjectText)
mc.setMessageBody(MessageBody.text, isHTML: false)
mc.setToRecipients(toRecipients)
self.presentViewController(mc, animated: true, completion: nil)
}
func mailComposeController(controller: MFMailComposeViewController!, didFinishWithResult result: MFMailComposeResult, error: NSError!) {
switch result.value{
case MFMailComposeResultCancelled.value:
NSLog("Mail Cancelled")
case MFMailComposeResultSaved.value:
NSLog("Mail Saved")
case MFMailComposeResultSent.value:
NSLog("Mail Sent")
case MFMailComposeResultFailed.value:
NSLog("Mail Sent Failure: %#",[error.localizedDescription])
default:
break
}
self.dismissViewControllerAnimated(true, completion: nil)
}
func loadAddressURL(){
let requestURL = NSURL(string:URLPath)
let request = NSURLRequest(URL: requestURL!)
Webview.loadRequest(request)
}
}
Make sure no warning message and bind all #IBOutlet in your ViewController.
Related
I'm trying to go next screen after the save button is pushed, i tried to write code perform segue and i get buch of errors. Below is my code currently, i didn't finish the save part. I wanted to go back to that later time.
I'm new to coding in xcode, so any advice on where to put this code would be nice.
import UIKit
import CoreData
class SignupVC: UIViewController {
#IBOutlet var txtfirstname: UITextField!
#IBOutlet var txtlastname: UITextField!
#IBOutlet var txtUsername: UITextField!
#IBOutlet var txtPassword: UITextField!
#IBOutlet var txtConfirmpassword: UITextField!
#IBOutlet var txtEmail: UITextField!
var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func signupTapped(_ sender: Any) {
_ = txtUsername.text;
_ = txtPassword.text;
_ = txtConfirmpassword.text;
_ = txtEmail.text;
//check empty fields
if((txtPassword.text?.isEmpty)! || (txtConfirmpassword.text?.isEmpty)! || (txtEmail.text?.isEmpty)!)
{
//Display alert
displayMyAlertMessage(userMessage: "All fields are required")
return;
}
//check if passwords match
if (txtPassword.text != txtConfirmpassword.text)
{
//Display in alert message
displayMyAlertMessage(userMessage: "Passwords don't match");
return;
}
//store Data
// Display alert message with Confirmation
}
func displayMyAlertMessage(userMessage:String)
{
let myAlert = UIAlertController(title:"Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title:"ok", style: UIAlertActionStyle.default, handler:nil);
myAlert.addAction(okAction);
self.present(myAlert, animated:true, completion:nil);
}
/*
just go into storyboard and hold control key on the button and let it go on the ViewController you want to go to. Then select the kind. For Example "Show"
then it should work. If you have questions ask.
I have a problem, I want to create a small app in which data in a formula can be charged.
Currently the data from three ViewControllers and one PickerViewController will be given back to the first ViewController.
That works very well too.
Now I want that the data at the start not on "nil" set but have a certain value.
Thereafter, the data entered last should reappear when the app is restarted.
I would like to apologize for my english, it is not my preferred language ...
Here is a part of my code how I wrote it
Main ViewController:
import UIKit
class RecivingViewController: UIViewController, SendDataBack, SendDataBack2, SendDataBack3, SendDataBack4 {
#IBOutlet weak var recivingData: UILabel!
#IBOutlet weak var recivingData2: UILabel!
#IBOutlet weak var recivingData3: UILabel!
#IBOutlet weak var recivingData4: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func userData(data: String) {
recivingData.text = data
}
func userData2(data: String) {
recivingData2.text = data
}
func userData3(data: String) {
recivingData3.text = data
}
func PickerData(data: String){
recivingData4.text = data
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "view1" {
let SendingVC: SendingViewController = segue.destination as! SendingViewController
SendingVC.delegate = self
}
if segue.identifier == "view2" {
let SendingVC2: Sending2ViewController = segue.destination as! Sending2ViewController
SendingVC2.delegate = self
}
if segue.identifier == "view3" {
let SendingVC3: Sending3ViewController = segue.destination as! Sending3ViewController
SendingVC3.delegate = self
}
if segue.identifier == "picker" {
let SendingVC4: PickerViewController = segue.destination as! PickerViewController
SendingVC4.delegate = self
}
}
}
one of the other ViewControllers:
import UIKit
protocol SendDataBack {
func userData(data: String)
}
class SendingViewController: UIViewController {
#IBOutlet weak var DataTxt: UITextField!
var delegate: SendDataBack? = nil
#IBAction func done(_ sender: Any) {
if delegate != nil {
if DataTxt.text != nil {
let data = DataTxt.text
delegate?.userData(data: data!)
dismiss(animated: true, completion: nil)
}
}
}
In order to see data after app is restarted you should use user defaults.
For saving data
UserDefaults.standard.set(newValue, forKey: "data")
For loading data in your view controller, if it's first load, when data is nil
UserDefaults.standard.string(forKey: "data")
I currently have my app linking to a certain URL upon opening the app, and this obviously can have a delay between opening it and the webView actually loading, so I want it to display an activity indicator whenever the webView is loading, I have the following code in my ViewController.swift:
class ViewController: UIViewController, UIWebViewDelegate {
#IBOutlet weak var webView: UIWebView!
#IBOutlet weak var activityIndicator: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
webView.delegate = self
let url = URL(string: "url to site")
webView.loadRequest(URLRequest(url: url!)
}
func webViewDidStartLoad(webView: UIWebView){
activityIndicator.startAnimating()
}
func webViewDidFinishLoad(webView: UIWebView){
activityIndicator.stopAnimating()
}
The activity indicator shows up from the beginning but it does not disappear once the webView loads and stays their forever.
The way you have your code organized is a bit confusing. It appears you are declaring your funcs inside the #IBAction function. If this is the case, this will not work.
Try this instead
class ViewController: UIViewController, UIWebviewDelegate {
override func viewDidLoad() {
...
webView.delegate = self
// You should add this to your Storyboard, above the webview instead of here in the code
activityIndicator.center = self.view.center
activityIndicator.hidesWhenStopped = true
activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
// I forget the actual method name - look it up
view.insertSubview(activityIndicator, above: webView)
}
#IBAction func openButton(_ sender: Any) {
let url = URL(string: "websiteURL")
webView.loadRequest(URLRequest(url: url!))
}
func webViewDidStartLoad(webView: UIWebView){
activityIndicator.startAnimating()
}
func webViewDidFinishLoad(webView: UIWebView){
activityIndicator.stopAnimating()
}
// You'll also want to add the "didFail" method
}
The issue is a syntax issue, you have to add an underscore in the functions.
override func viewDidLoad() {
super.viewDidLoad()
webView.delegate = self
let url = URL(string: "your URL")
webView.loadRequest(URLRequest(url: url!))
}
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool{
activityIndicator.startAnimating()
return true
}
func webViewDidStartLoad(_ webView: UIWebView){
activityIndicator.startAnimating()
}
func webViewDidFinishLoad(_ webView: UIWebView){
activityIndicator.stopAnimating()
}
func webView(_ webView: UIWebView, didFailLoadWithError error: Error){
activityIndicator.stopAnimating()
}
I am working on a Mac OS X application with Swift.
This is my first time and I thought it would be the same as it is on iOS.
So I got this error (in the title) on this code:
import Cocoa
import AppKit
class LoginViewController: NSViewController {
#IBOutlet weak var emailTextField: NSTextField!
#IBOutlet weak var passwordTextField: NSSecureTextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewDidAppear() {
}
super.viewDidAppear()
if NSUserDefaults.standardUserDefaults().valueForKey("uid") != nil && CURRENT_USER!.authData != nil
{
self.logoutButton.hidden = false
}
}
func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
func loginAction(sender: AnyObject)
{
let email = self.emailTextField.text
let password = self.passwordTextField.text
...
}
}
What do I have to write instead of self?
Using self is correct. Try using the property stringValue instead of text.
Here is the code that worked for me:
#IBOutlet weak var emailTextField: NSTextField!
#IBAction func sendTapped(sender: AnyObject) {
let email = self.emailTextField.stringValue
print(email)
}
I am trying to make a small iPad application which features an 'About' page. I have run into an issue when I try to change the class of the about page scene which is displayed modally, as the application crashes when the user tries to access this page. I wish to change its class to "ViewController", which is the same class as my main window (map view), to create actions from buttons on the 'About' page.
Currently I am unable to ctrl+drag to the .Swift file from the About page unless I change its class. Not sure why this is happening :(
The error printed to the console is as follows:
fatal error: unexpectedly found nil while unwrapping an Optional value
0 specialised_fatalErrorMessage(StaticString, StaticString, StaticString, Uint) -> () –
Here is my storyboard with scenes:
Here is the full ViewController.Swift code:
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate, UISearchBarDelegate, UIPopoverPresentationControllerDelegate {
var location: CLLocation!
let locationManager = CLLocationManager()
// Map variables
var searchController:UISearchController!
var annotation:MKAnnotation!
var localSearchRequest:MKLocalSearchRequest!
var localSearch:MKLocalSearch!
var localSearchResponse:MKLocalSearchResponse!
var error:NSError!
var pointAnnotation:MKPointAnnotation!
var pinAnnotationView:MKPinAnnotationView!
#IBOutlet weak var mapView: MKMapView!
#IBOutlet weak var segmentedControl: UISegmentedControl!
#IBOutlet weak var showSearchBar: UIBarButtonItem!
#IBOutlet weak var addButton: UIBarButtonItem!
#IBOutlet weak var moreStuff: UIBarButtonItem!
#IBAction func addButton(sender: AnyObject) {
let annotation = MKPointAnnotation()
annotation.coordinate = CLLocationCoordinate2D(latitude: self.mapView.userLocation.coordinate.latitude, longitude: self.mapView.userLocation.coordinate.longitude)
self.mapView.addAnnotation(annotation)
self.locationManager.startUpdatingLocation()
}
#IBAction func showSearchBar(sender: UIBarButtonItem!) {
searchController = UISearchController(searchResultsController: nil)
searchController.hidesNavigationBarDuringPresentation = false
self.searchController.searchBar.delegate = self
presentViewController(searchController, animated: true, completion: nil)
}
#IBAction func moreStuff(sender: AnyObject) {
self.performSegueWithIdentifier("showMoreStuff", sender:self)
}
#IBAction func refresh(sender: AnyObject) {
self.locationManager.startUpdatingLocation()
}
#IBAction func segmentedControl(sender: UISegmentedControl!) {
if sender.selectedSegmentIndex == 0{
mapView.mapType = MKMapType.Standard
}
else if sender.selectedSegmentIndex == 1{
mapView.mapType = MKMapType.Satellite
}
else if sender.selectedSegmentIndex == 2{
mapView.mapType = MKMapType.Hybrid
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
self.mapView.showsUserLocation = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// location delegate methods
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.last
let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
self.mapView.setRegion(region, animated: true)
self.locationManager.stopUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError)
{
print("Error code: " + error.localizedDescription)
}
func searchBarSearchButtonClicked(searchBar: UISearchBar){
searchBar.resignFirstResponder()
dismissViewControllerAnimated(true, completion: nil)
if self.mapView.annotations.count != 0{
annotation = self.mapView.annotations[0]
self.mapView.removeAnnotation(annotation)
}
localSearchRequest = MKLocalSearchRequest()
localSearchRequest.naturalLanguageQuery = searchBar.text
localSearch = MKLocalSearch(request: localSearchRequest)
localSearch.startWithCompletionHandler { (localSearchResponse, error) -> Void in
if localSearchResponse == nil{
let alertController = UIAlertController(title: nil, message: "No Such Place", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
return
}
self.pointAnnotation = MKPointAnnotation()
self.pointAnnotation.title = searchBar.text
self.pointAnnotation.coordinate = CLLocationCoordinate2D(latitude: localSearchResponse!.boundingRegion.center.latitude, longitude: localSearchResponse!.boundingRegion.center.longitude)
self.pinAnnotationView = MKPinAnnotationView(annotation: self.pointAnnotation, reuseIdentifier: nil)
self.mapView.centerCoordinate = self.pointAnnotation.coordinate
}
}
}
I am new to Swift so any help is really appreciated. Thanks!
Edit:
This is the error screen presented to me once the app crashes:
I haven't used mapKit but I still try.
Looking at your error your getting a nil crash, which indicates one of your properties is nil yet you try to use it.
Having a quick read through your code it seams you haven't initialised
var localSearchResponse....
Again i don't know the MK API very well so I am not 100 sure what I'm saying is relevant.
Have you checked that all your IBOutlets are properly connected?
On which line do you get the crash when this happens? Do you get the crash before or after changing to the abouts page?