2014-12-27 3 views
0

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 { <--thread 1 signal sigarbt

콘솔에 다른 것을 표시하지 않습니다. 무엇이 문제 일 수 있습니까?

// 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 수입 기금

01 23,516,

클래스의 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 파일 없어요.

+1

충돌이 발생한 행을 확인하십시오. func reload()에서 중단 점을 사용하고 충돌이 발생한 위치를 확인합니다. 좀 더 자세히 디버깅하려면 reload 함수에 아래 조건을 넣습니다. if (refreshButton.hidden) {refreshButton.hidden = false; } else {refreshButton.hidden = true;} 이것이 작동하는지 확인하십시오. 또한 버튼 및 활동 표시기 초기화시 더 많은 코드를 게시하십시오. –

+0

@ArunGupta func에서 모든 코드를 삭제하려고 시도했지만 계속 충돌합니다. –

+0

@ArunGupta가 (버튼을 확인하려고 시도했습니다.= nil)하지만 작동하지 않았습니다 –

답변

0

reload 함수가 호출되는 중입니까? storyboard/Xib를 사용하여 UIButton을 만드는 경우 touchUpInside 이벤트에서 Xib의 reload 함수를 연결하거나 코드에서 UIButton 이벤트를 만드는 경우 다음과 같이 코드를 작성합니다.

.h 파일에 다른 UIButton 속성을 만듭니다. @ 속성 (비 원자력, 강함) UIButton * 새로 고침; 하는 .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; 
    } 
} 
+0

스토리 보드를 사용 중입니다. alt 키를 누르고 버튼을 내 ViewController.swift로 드래그하고 액션 IBAction을 만듭니다. 이 코드는 어디에 두어야합니까? 죄송합니다.하지만 iOS 프로그래밍을 처음 접했습니다. –

+0

스토리 보드를 사용하고 스토리 보드를 사용하여 IBAction을 만드는 경우이 기능이 자동으로 생성됩니다. 이 함수가 호출되고 있습니까? 함수에 중단 점을 넣고 내부에 중단 점이 있는지 확인합니다. 그 안에 NSLog 만 넣으십시오. 위의 코드는 무시하십시오. –

+0

아니요, 프로그램이 함수 안에 들어 가지 않습니다. 버튼을 클릭하면 앱이 다운됩니다. 기능 또는 아닙니다. 나는 이것을 정말로 이해할 수 없다. –

0

작동 좋아! 이유를 묻지 마십시오. 간단히 코드를 삭제하고 다시 작성했습니다. 그리고 그것은 작동합니다. 마법이라고 부르세요. 답변 해 주셔서 감사합니다.