logo
down
shadow

Basic Authentication with AFNetworking


Basic Authentication with AFNetworking

By : user2949771
Date : November 17 2020, 04:28 AM
it should still fix some issue You need to put your authentication to headers. You can do it in this way:
code :
//creating crequest    
NSURL *url = [NSURL URLWithString:YOUR_URL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

//Encode username and password

NSData *plainData = [[NSString stringWithFormat:@"%@:%@", username, password] dataUsingEncoding:NSUTF8StringEncoding];
NSString *encodedUsernameAndPassword = [plainData base64EncodedStringWithOptions:0];

//set auth header
[request addValue:[NSString stringWithFormat:@"Basic %@", encodedUsernameAndPassword] forHTTPHeaderField:@"Authorization"];

// your AFNetworking code


Share : facebook icon twitter icon
Using AFNetworking and HTTP Basic Authentication

Using AFNetworking and HTTP Basic Authentication


By : Atso S
Date : March 29 2020, 07:55 AM
may help you . The following code successfully connects to my Ruby on Rails API and returns JSON using AFNetworking. What do I need to do to edit this to pass in a username and password so my API can use HTTP Basic Authentication? , Answer updated for AFNetworking 2.x
For AFNetworking 2.x:
code :
#import "AFHTTPRequestOperationManager.h"

@interface SBAPIManager : AFHTTPRequestOperationManager

- (void)setUsername:(NSString *)username andPassword:(NSString *)password;

+ (SBAPIManager *)sharedManager;

@end
#import "SBAPIManager.h"
#import "AFNetworkActivityIndicatorManager.h"

@implementation SBAPIManager

#pragma mark - Methods

- (void)setUsername:(NSString *)username andPassword:(NSString *)password
{
    [self.requestSerializer clearAuthorizationHeader];
    [self.requestSerializer setAuthorizationHeaderFieldWithUsername:username password:password];
}

#pragma mark - Initialization

- (id)initWithBaseURL:(NSURL *)url
{
    self = [super initWithBaseURL:url];
    if(!self)
        return nil;

    self.requestSerializer = [AFJSONRequestSerializer serializer];

    [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];

    return self;
}

#pragma mark - Singleton Methods

+ (SBAPIManager *)sharedManager
{
    static dispatch_once_t pred;
    static SBAPIManager *_sharedManager = nil;

    dispatch_once(&pred, ^{ _sharedManager = [[self alloc] initWithBaseURL:[NSURL URLWithString:@"http://localhost:3000"]]; }); // You should probably make this a constant somewhere
    return _sharedManager;
}

@end
[[SBAPIManager sharedManager] setUsername:yourUsernameVariableHere andPassword:yourPasswordVariableHere];

[[SBAPIManager sharedManager] GET:@"/tasks.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
    self.tasks = [responseObject objectForKey:@"results"];
    [self.activityIndicatorView stopAnimating];
    [self.tableView setHidden:NO];
    [self.tableView reloadData];

    NSLog(@"JSON");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    // error stuff here
}];
#import "AFNetworking/AFHTTPClient.h"

@interface SBAPIManager : AFHTTPClient

- (void)setUsername:(NSString *)username andPassword:(NSString *)password;

+ (SBAPIManager *)sharedManager;

@end
#import "SBAPIManager.h"
#import "AFJSONRequestOperation.h"
#import "AFNetworkActivityIndicatorManager.h"

@implementation SBAPIManager

#pragma mark - Methods

- (void)setUsername:(NSString *)username andPassword:(NSString *)password
{
    [self clearAuthorizationHeader];    
    [self setAuthorizationHeaderWithUsername:username password:password];
}

#pragma mark - Initialization

- (id)initWithBaseURL:(NSURL *)url
{
    self = [super initWithBaseURL:url];
    if(!self)
        return nil;

    [self registerHTTPOperationClass:[AFJSONRequestOperation class]];
    [self setDefaultHeader:@"Accept" value:@"application/json"];
    [self setParameterEncoding:AFJSONParameterEncoding];

    [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];

    return self;
}

#pragma mark - Singleton Methods

+ (SBAPIManager *)sharedManager
{
    static dispatch_once_t pred;
    static SBAPIManager *_sharedManager = nil;

    dispatch_once(&pred, ^{ _sharedManager = [[self alloc] initWithBaseURL:[NSURL URLWithString:@"http://localhost:3000"]]; }); // You should probably make this a constant somewhere
    return _sharedManager;
}

@end
[[SBAPIManager sharedManager] setUsername:yourUsernameVariableHere andPassword:yourPasswordVariableHere];

[[SBAPIManager sharedManager] getPath:@"/tasks.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
    self.tasks = [responseObject objectForKey:@"results"];
    [self.activityIndicatorView stopAnimating];
    [self.tableView setHidden:NO];
    [self.tableView reloadData];

    NSLog(@"JSON");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    // error stuff here
}];
AFNetworking 2.0 and HTTP Basic Authentication

AFNetworking 2.0 and HTTP Basic Authentication


By : Tatman
Date : March 29 2020, 07:55 AM
it should still fix some issue AFNetworking 2.0 new architecture use serializers for creating requests and parsing responses. In order to set the authorization header, you should first initialize a request operation manager that replaces the AFHTTPClient, create a serializer and then call the dedicated method to set the header.
For example you code would become:
code :
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:@"http://examplewebsite.com"]];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:@"userName" password:@"password"];
IOS - Basic Authentication with a REST API - SSL - AFNetworking 3.0

IOS - Basic Authentication with a REST API - SSL - AFNetworking 3.0


By : Andreas Mavrommatis
Date : March 29 2020, 07:55 AM
Hope that helps I'm guessing you're intending to use HTTP Basic Authentication in which case you should be using the Authorization header field instead of passing the username and password in plain text within the request's parameters (I made this mistake the first time I tried to do Basic Authentication with a REST API).
You will need to add it to the AFHTTPRequestSerializer's headers which you can do by utilizing the setAuthorizationHeaderFieldWithUsername:password: method or by constructing the header field value manually and setting the header field value using the setValue:forHTTPHeaderField: method.
Resetting basic authentication credentials with AFNetworking

Resetting basic authentication credentials with AFNetworking


By : Yijun Xiao
Date : March 29 2020, 07:55 AM
wish helps you Use AFHTTPClient (see the API client in the example project).
Credentials can be set with -setAuthorizationHeaderWithUsername:password:. Each request created from that HTTP client will have an Authorization HTTP header, kind of like a browser session.
401 error - Basic Authentication with AFNetworking AFHTTPClient & Tastypie

401 error - Basic Authentication with AFNetworking AFHTTPClient & Tastypie


By : semicondoctor
Date : March 29 2020, 07:55 AM
seems to work fine Based on this: https://github.com/AFNetworking/AFNetworking/issues/426
I override the - (void)getPath:(NSString *)path parameters... method in the AFHTTPClient subclass to look something like this:
Related Posts Related Posts :
  • Warning: "Could not get traitsetID for iPhone11,6" (Assets.xcassets)
  • Changing root view controller after iOS app has loaded.
  • SocketRocket and iOS certificate pinning
  • Draggable UIButton Snap To a Circle Path
  • Running FireBase in the background
  • resizing UIPopoverController to fit UITableController
  • UICollectionView Exception Crash
  • targeting iOS5 - will it work on iOS6 also?
  • FBLoginView get email
  • Scale UIImages height to UIImageView height
  • Creating a custom progress indicator in ios
  • NSRunLoop API difference
  • Is it possible to inject custom settings into my iOS application "Notifications" settings dialog?
  • UIAlertview not accepting string as message
  • Axis change of stackView giving layout error
  • How to use AVAssetResourceLoader?
  • How to write block definition using properties?
  • iOS connect/reconnect to Bluetooth device when using external-accessory and MFi
  • Saving XMPP Multi User chat messages through XMPP MessageArchiving in iOS
  • Deciding iOS version: pros and cons
  • iOS: Resigned app cannot access keychain through security API
  • How can I set To and Subject fields in an E-Mail being sent by UIDocumentInteractionController?
  • Updating uilabel in view controller underneath another
  • Maximum time Intervel for NSTimer
  • Delete Core Data Entry from Table View Controller
  • How to unload UIViewcontroller from memory?
  • Compressing UIImage as Far as Possible?
  • Optimizing workflow to update internally owned cocoapods dependencies?
  • Formatting an NSDate with Abbreviated Month/Day Names
  • I'm creating a quiz game with 4 answers and I want to add score
  • Tap Gesture to Hide Navigation Bar, Tab Bar, and Status Bar
  • FBSessionStateClosedLoginFailed when I am logged in through Settings
  • CGRect positioning according to center point
  • iOS: Update table view datasource with animations without core data
  • iOS : Where to start for AliPay integration?
  • Routing App Coverage File missing but not needed?
  • Drawing on a zoomable view
  • Append NSStrings and NSNumber to NSMutableArrays and make NSMutable dictionary
  • Terminating app due to uncaught exception 'NSRangeException' when calling dequeueReusableCellWithReuseIdentifier:forInde
  • Collision without physics (Cocos2D + Box2D iOS)
  • Creating a percentage based iOS layout
  • Update tableView row from AppDelegate Swift 4
  • Assigning return value of a class method to a variable error
  • how to display circular progress in delphi ios apps?
  • I can't figure how to fix this Expected identifier or '('
  • How to Test APIs in Swift 4?
  • Link error /Build/Products/Debug-iphonesimulator file not found
  • working with a very large JSON object in iOS
  • Turn off part of the iPhone Screen
  • Phonegap 3.0 app with facebook login using xCode
  • How to add interstitial admob ads to my ios project
  • adding tapku calendar to ios app
  • Add an alertcontroller in a global swift file?
  • Take square image with Cordova (Phonegap) Camera API?
  • Amazon S3 policy allowing only upload not overwrite
  • How to change the UILabel content by tapping?
  • Adding checkmark to selected table cell also checks another table cell
  • UICollectionView cellForItemAtIndexPath indexPath row is nil
  • Resize and set quality on JPEG image while retaining EXIF in iOS
  • How to push rootviewcontroller in Ios
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org