2016-08-05 85 views
1

在ViewController中,我啓動了Location.swift中的類Location,以便使用它的方法。如何從swift委託類方法將數據傳回ViewController?

in ViewDidLoad,我打電話給Location的第一個方法,它建立了位置服務(權限等)。同樣在Location中,有兩個來自CLLocationManagerDelegate的委託方法。

視圖控制器看起來像(簡體!):

class ViewController: UIViewController { 
    var location = Location(); 
    override func viewDidLoad() { 
      location.initLocation(); 
      //when updated data from delegated method, i want to get data to here, in order to output it in UI labels,etc 
    } 
} 

Location.swift樣子(簡化!):

import CoreLocation 

class Location: NSObject, CLLocationManagerDelegate{ 
     func initLocation(){ 
     ........ 
     } 

     @objc func locationManager(manager: CLLocationManager, didUpdateHeading newHeading: CLHeading){ 
      //i want to send newHeading data to viewController here 
     } 

} 

我可以很容易地從initLocation()找回數據,如我所說,並定義該方法我自己。但是如果我需要從locationManager方法獲取數據,那麼我不會調用該數據呢?

請問如果您有任何問題。我希望我已經充分解釋了!

乾杯

+0

你需要的newHeading值每次它更新或做你想做的只是能夠調用這個類來獲取newHeading最近的值? – KotaBear233

+0

你應該使用...代表團!創建一個協議,例如'LocationDelegate',並通過你的'ViewController'實現它。 – Losiowaty

+0

@ KotaBear233每當它更新:) –

回答

0

你可以嘗試位置創建一個新的委託,如:

ViewController.swift

class ViewController: UIViewController, LocationDeleate { 

    var location = Location() 

    override func viewDidLoad() { 

     location.deleagte = self 
     //location.initLocation() 
    } 

    func initLocation() { 

     //when updated data from delegated method, i want to get data to here, in order to output it in UI labels,etc 
    } 
} 

然後創建一個新的協議迅速文件:

LocationProtocol.swift

protocol LocationProtocol : class { 
    func initLocation() 
} 

Location.swift

import CoreLocation 

class Location: NSObject, CLLocationManagerDelegate{ 

    weak var delegate : LocationDelegate? 

    @objc func locationManager(manager: CLLocationManager, didUpdateHeading newHeading: CLHeading){ 

     // send notification to parent view controller 
     delegate?.initLocation() 
    } 
} 
+0

謝謝。當你把class關鍵字放在協議定義名稱後面時,這意味着什麼? –

+0

這將協議標記爲只能由類使用,如果刪除「:class」,則會在委託對象中發生此錯誤:「'weak'只能應用於類和類綁定協議類型,而不應用於'LocationProtocol' 」。 – DTHENG

相關問題