AFNetworking include headers

2019-06-21 19:54发布

问题:

I'm trying to convert from ASIHttpRequest to AFNetworking but I seem to be having a "Use of undeclared identifier AFURLSessionManager" error on the following line in my class.

AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

I have included the following on my header:

#import "AFNetworking.h"
#import "AFURLSessionManager.h"

It must be something really obvious, but having a bad brain fart right now.

回答1:

The behavior is simply explained by this line of code in AFURLSessionManager.h

#if (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000) || (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090)

AFURLSessionManager makes use of NSURLSession, which is available from iOS 7 (and OSX 10.9) on.

If you are targeting iOS 6, AFURLSessionManager just can't be used and it's stripped out at compile time. That's why you get the error.

Setting iOS 7 as minimum deployment target will fix the compile error, even though it may not fit your needs.


That said, my suggestions is to use CocoaPods to managed third-party dependencies, such as AFNetworking.

AFNetworking 2.0 is a modular framework, meaning that you can pick which modules to use according to your needs. The core supports iOS 6, but some modules only support iOS 7, such as the NSURLSession module which is the one where AFURLSessionManager belongs.

Modularity is achieved by using CocoaPods subspecs. In order to import AFNetworking and the NSURLSession module, you will just have to do something like

platform :ios, '7.0'

pod 'AFNetworking',              '~> 2.0'
pod 'AFNetworking/NSURLSession', '~> 2.0'

You still can target iOS 6, but you won't get the incompatible submodules, as specified in the CocoaPods documentation.

A subspec can restrict the platform of the parent specification. In this case it will be inherited by the parent specification only if the target of the podfile supports it.