簡體   English   中英

按下重新加載按鈕時應用崩潰

[英]App crash when reload button is pressed

我的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類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導入UIKit導入基礎

類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文件。

重載函數甚至被調用嗎? 如果您使用情節提要/ Xib創建UIButton,則在touchUpInside Event上的Xib中鏈接重載函數,或者如果您在代碼中創建UIButton事件,則如下所示:

在.h文件中創建另一個UIButton屬性:@property(nonatomic,strong)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;
    }
}

好吧,行得通! 請不要問我為什么:)我只是刪除了代碼並重寫了它。 而且有效。 稱之為魔術。 謝謝大家的答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM