Alamofire相当于AFHTTPSessionManager

Tra*_*ggs 5 afnetworking afnetworking-2 swift alamofire

随后AFNetworking我遵循了创建特定于应用程序的子类的建议模式AFHTTPSessionManager.我看起来像这样:

static NSString* Username = @"";
static NSString* Password = @"";
static NSString* BaseURL = @"https://abc.xyz.com:12345/";

@implementation HttpConnection

+ (HttpConnection*) current {
    static HttpConnection* current = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        current = [[self alloc] initWithBaseURL: [NSURL URLWithString: BaseURL]];
        current.securityPolicy.allowInvalidCertificates = YES;
        current.responseSerializer = [AFJSONResponseSerializer serializer];
        current.requestSerializer = [AFJSONRequestSerializer serializer];
    });
    [current.requestSerializer setAuthorizationHeaderFieldWithUsername: Username password: Password];
    return current;
}
Run Code Online (Sandbox Code Playgroud)

我很好奇我应该如何翻译这个模式Alamofire.它只是如下吗?

static let BaseURL = "https://abc.xyz.com:12345/"
static var User = ""
static var Password = ""

func myAppRequest((method: Method, URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL) -> Request {
    let request = Alamofire.request(method, BaseURL + URLString, parameters, encoding)
    request.authenticate(user: User, password: "Password)
    return request
}
Run Code Online (Sandbox Code Playgroud)

Alamofire代码中偷看,我有一种预感,即可以Alamofire.Manager.sharedInstance在适当的时间进行操作(app启动时的baseURL,以及每当更改时的用户/密码).但是那个人如何做到这一点并不那么明显(如果确实可能的话).

Mea*_*her 0

我正在使用 Alamofire.Manager 来处理所有请求。我就是这样做的。

//initialize with all details such as referrer etc
self.manager = Alamofire.Manager(configuration: cfg) 


let user = "user"
let password = "password"
// you may manipulate configuration later on if you want.
self.manager.session.configuration.HTTPAdditionalHeaders!["Referer"] = self.host
self.manager.request(.GET, "https://httpbin.org/basic-auth/\(user)/\(password)")
         .authenticate(user: user, password: password)
         .responseJSON { (req, res, json, error) in
            if(error != nil) {
                NSLog("Error: \(error)")
                failure(res, json, error)
                return
            }
            else {
                 // do something with JSON
    }
}
Run Code Online (Sandbox Code Playgroud)

  • mngr 只是让我的灵魂痛苦。为了您和任何阅读您代码的人的利益,在命名事物时请使用实际的单词。 (3认同)