I'm not very experienced in iOS development. While making subclass of AFHTTPSessionManager
XCode suggested me to include required init(coder)
:
import UIKit
let _sharedAPIManager = APIManager(baseURL: NSURL(string: API_URL)!)
class APIManager: AFHTTPSessionManager {
/**
* Singleton service
* (https://github.com/hpique/SwiftSingleton)
*/
class var sharedInstance : APIManager {
return _sharedAPIManager
}
init(baseURL url: NSURL!) {
super.init(baseURL: url, sessionConfiguration: nil)
self.responseSerializer = AFJSONResponseSerializer() as AFJSONResponseSerializer
self.requestSerializer = AFJSONRequestSerializer() as AFJSONRequestSerializer
self.requestSerializer.setValue(API_KEY, forHTTPHeaderField: "X-Api-Key")
self.requestSerializer.setValue("3", forHTTPHeaderField: "X-Api-Version")
}
// this was inserted by XCode
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
My main question is why it's required? As far as I know NSCoder
deals with storyboards related code (e.g. called when the nib loads).
Related question Class does not implement its superclass's required members contains some info but does it mean that all Swift classes that extend Objective-C ones will need it?
initWithCoder:
and encodeWithCoder:
are used any time you encode and decode objects, usually for writing to / reading from disk. You're right that storyboards use this, but it's also a very common way to save data in between app launches.
AFHTTPSessionManager
implements this method so that you can encode your session manager if you want. Because it's implemented there, you must override it in your subclass, and set or decode any non-optional properties before you call super.
来源:https://stackoverflow.com/questions/29320083/swift-why-initcoder-is-required-in-afhttpsessionmanager