objective-cswiftafhttprequestoperation

Swift errors: 'manager()' is unavailable: use object construction 'AFHTTPRequestOperationManager()'


I have this swift code that I think should work but it can't handle objective c static fields. I have tried to add "()" multiple places but nothing works.

func AFHTTPRequestOperationManagerDispatchOnMainQueue(mainQueue: Bool) -> AFHTTPRequestOperationManager {
    var manager = AFHTTPRequestOperationManager.manager
    manager.responseSerializer = AFJSONResponseSerializer(readingOptions: NSJSONReadingOptions.AllowFragments)
    manager.requestSerializer = AFJSONRequestSerializer(readingOptions: NSJSONReadingOptions.AllowFragments)
    if (!mainQueue) {
        manager.completionQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
    }
    return manager;
}

The field and properties looks like this:

+ (instancetype)manager;
@property (nonatomic, strong) AFHTTPRequestSerializer <AFURLRequestSerialization> * requestSerializer;
@property (nonatomic, strong) AFHTTPResponseSerializer <AFURLResponseSerialization> * responseSerializer;

I get those error messages:

Error: 'manager()' is unavailable: use object construction 'AFHTTPRequestOperationManager()'
Error: '() -> AFHTTPRequestOperationManager!' does not have a member named 'responseSerializer'
Error: '() -> AFHTTPRequestOperationManager!' does not have a member named 'requestSerializer'
Error: '() -> AFHTTPRequestOperationManager!' does not have a member named 'completionQueue'
Error: function produces expected type 'AFHTTPRequestOperationManager!'; did you mean to call it with '()'?


Solution

  • When Objective-C is imported into Swift, as you're doing with AFNetworking here, identifiable factory methods are converted to simple initializers. In this case that means that (as @Martin points out) you should be using that form instead:

    var manager = AFHTTPRequestOperationManager()