Сбой приложения при нажатии кнопки перезагрузки

У меня проблемы с приложением погоды для iOS. Я новичок в программировании в xCode, поэтому это может быть глупая ошибка. В любом случае проблема в том, что я пытаюсь добавить кнопку обновления в свое одностраничное приложение. С кнопкой связана функция IBAction, поэтому при нажатии она должна быть скрыта и должен появиться индикатор активности. Это функция:

@IBAction func reload () {

    refreshButton.hidden = true
    refreshActivityIndicator.hidden = false
    refreshActivityIndicator.startAnimating()

}

и это объявление переменных:

@IBOutlet weak var refreshButton: UIButton!
@IBOutlet weak var refreshActivityIndicator: UIActivityIndicatorView!

когда я запускаю приложение и нажимаю кнопку обновления, приложение вылетает, и я получаю эту ошибку:

@UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate {‹- сигнатура сигнала потока 1

консоль больше ничего не показывает. В чем может быть проблема?

// APPDELEGATE.SWIFT

импорт UIKit

@UIApplicationMain класс AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?


func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.

    application.setStatusBarHidden(true, withAnimation: .None)

    return true
}

func applicationWillResignActive(application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

func applicationDidEnterBackground(application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

func applicationWillEnterForeground(application: UIApplication) {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

func applicationDidBecomeActive(application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

func applicationWillTerminate(application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

}

//VIEWCONTROLLER.SWIFT import UIKit import Foundation

class ViewController: UIViewController {

private let apiKey = "447073dc853014a6fa37376c43d8462b"

@IBOutlet weak var iconView: UIImageView!
@IBOutlet weak var currentTimeLabel: UILabel!
@IBOutlet weak var temperatureLabel: UILabel!
@IBOutlet weak var humidityLabel: UILabel!
@IBOutlet weak var precipitationLabel: UILabel!
@IBOutlet weak var summaryLabel: UILabel!

@IBOutlet weak var refreshButton: UIButton!

@IBOutlet weak var refreshActivityIndicator: UIActivityIndicatorView!


override func viewDidLoad() {

    super.viewDidLoad()

    // Do any additional setup after loading the view, typically from a nib.

    refreshActivityIndicator.hidden = true

    // base URL

    let baseURL = NSURL(string: "https://api.forecast.io/forecast/\(apiKey)/")

    // add coordinates to base url (API syntax)

    let forecastURL = NSURL(string: "44.698150,10.656846", relativeToURL: baseURL)

    // NSURL SESSION 
    //The NSURLSession class and related classes provide an API for downloading content via HTTP. This API provides a rich set of delegate methods for supporting authentication and gives your app the ability to perform background downloads when your app is not running or, in iOS, while your app is suspended. With the NSURLSession API, your app creates a series of sessions, each of which coordinates a group of related data transfer tasks. For example, if you are writing a web browser, your app might create one session per tab or window. Within each session, your app adds a series of tasks, each of which represents a request for a specific URL (and for any follow-on URLs if the original URL returned an HTTP redirect).

    let sharedSession = NSURLSession.sharedSession()



    let downloadTask : NSURLSessionDownloadTask = sharedSession.downloadTaskWithURL(forecastURL!, completionHandler:

        { (location: NSURL!, response: NSURLResponse!, error: NSError!) -> Void in

        if (error == nil) {

            let dataObject = NSData(contentsOfURL: location) // convert in NSData object

            // serialize NSData object in Json as Dictionary

            let weatherDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataObject!, options: nil, error: nil) as NSDictionary

            // instance of Current (Current.swift) init with weatherDictionary

            let currentWeather = Current(weatherDictionary: weatherDictionary)


            // we put the code in the main queue cause this is relative the UI, that have the first thread (concurrency)

            dispatch_async(dispatch_get_main_queue(), { () -> Void in

                self.temperatureLabel.text = "\(currentWeather.temperature)"
                self.iconView.image = currentWeather.icon!
                self.currentTimeLabel.text = "At \(currentWeather.currentTime!) it is"
                self.humidityLabel.text = "\(currentWeather.humidity)"
                self.precipitationLabel.text = "\(currentWeather.precipProbability)"
                self.summaryLabel.text = "\(currentWeather.summary)"

                // Stop refresh animation

                self.refreshActivityIndicator.stopAnimating()
                self.refreshActivityIndicator.hidden = true
                self.refreshButton.hidden = false

            })

        }


    })

    downloadTask.resume() // call sharedSession.downloadTaskWithURL -> store json data in location (local temporary memory)


}


@IBAction func reload() {
    println("PRESSED")
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

У меня нет файлов .h или .m.


person Giuseppe Capoluongo    schedule 27.12.2014    source источник
comment
Пожалуйста, проверьте, в какой строке происходит сбой. Используйте точку останова в функции reload () и посмотрите, где происходит сбой. Для более подробной отладки поставьте условие ниже в функции перезагрузки if (refreshButton.hidden) {refreshButton.hidden = false; } else {refreshButton.hidden = true;} и посмотрите, работает ли это. Также, пожалуйста, разместите больше кода для инициализации кнопки и индикатора активности.   -  person Arun Gupta    schedule 27.12.2014
comment
@ArunGupta Я попытался удалить весь код в func, но он продолжает вылетать   -  person Giuseppe Capoluongo    schedule 27.12.2014
comment
@ArunGupta также пытался проверить (button! = Nil), но это не сработало   -  person Giuseppe Capoluongo    schedule 27.12.2014
comment
вы проверили установку свойства как сильного   -  person YaBoiSandeep    schedule 27.12.2014
comment
@ サ ン デ ィ ー プ нет, не слышал. Я следую за курсом teamtreehouse, и я сделал все в точности, как учитель.   -  person Giuseppe Capoluongo    schedule 27.12.2014
comment
@ サ ン デ ィ ー プ, ладно, я пробовала, но не сработало   -  person Giuseppe Capoluongo    schedule 27.12.2014
comment
@IBAction func reload (отправитель: AnyObject)   -  person Leo Dabus    schedule 27.12.2014
comment
@LeonardoSavioDabus пробовал, но это не решило проблему.   -  person Giuseppe Capoluongo    schedule 27.12.2014
comment
пытался поставить точку останова перед reload (), но все равно вылетел. Это проблема UIButton? Возможно ли такое?   -  person Giuseppe Capoluongo    schedule 27.12.2014
comment
Убедитесь, что кнопка подключена   -  person Leo Dabus    schedule 27.12.2014
comment
Я думаю, что это. Как я могу это проверить?   -  person Giuseppe Capoluongo    schedule 27.12.2014


Ответы (2)


Вызывается ли функция перезагрузки? Если вы используете раскадровку / Xib для создания UIButton, тогда свяжите функцию перезагрузки в Xib с событием touchUpInside или если вы создаете событие UIButton в коде, как показано ниже:

Создайте еще одно свойство UIButton в файле .h: @property (неатомное, сильное) UIButton * refresh;

В файле .m

-(void) viewDidLoad {
self.refresh = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[self.refresh addTarget:self 
       action:@selector(reload:) forControlEvents:UIControlEventTouchUpInside];
[self.refresh setTitle:@"Reload" forState:UIControlStateNormal];
self.refresh .frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[self.view addSubview:self.refresh];
}


-(void) reload:(UIButton*)sender
{
    NSLog(@"you clicked on button %@", sender.tag);
    if(self.refresh.hidden) {
        self.refresh.hidden = false;
    } else {
        self.refresh.hidden = true;
    }
}
person Arun Gupta    schedule 27.12.2014
comment
Я использую раскадровку. Просто нажмите alt и перетащите кнопку в мой ViewController.swift и создайте действие IBAction. Куда мне поместить этот код? Извините, но я новичок в программировании под iOS. - person Giuseppe Capoluongo; 27.12.2014
comment
Если вы используете раскадровку и создаете IBAction с помощью раскадровки, эта функция будет создана автоматически. Вызывается ли эта функция? Поставьте точку останова на функцию и посмотрите, не попадет ли она внутрь. Поместите в него просто NSLog. Игнорируйте приведенный выше код. - person Arun Gupta; 27.12.2014
comment
Нет, программа не входит в функцию. Когда я нажимаю кнопку, приложение вылетает. Функ или нет. Я действительно не могу этого понять. - person Giuseppe Capoluongo; 27.12.2014
comment
Пожалуйста, опубликуйте свои .h, .m и раскадровку с обнаруженным инспектором - person Arun Gupta; 27.12.2014
comment
Я сделал, но у меня всего два файла .swift. Нет файлов .h или .m. Я не могу публиковать изображения, поэтому не могу поделиться раскадровкой. - person Giuseppe Capoluongo; 27.12.2014

Хорошо, работает! Пожалуйста, не спрашивайте почему :) Я просто удалил код и переписал его. И это работает. Назовите это магией. Спасибо всем за ответы.

person Giuseppe Capoluongo    schedule 27.12.2014