Using Smart Proxy Manager with Objective-C#
Warning
zyte-smartproxy-ca.crt
should be installed in your OS for the below code to work. You can follow these instructions in order to install it.
Note
All the code in this documentation has been tested with Xcode 13.1.
In order to work with Objective-C make sure you have Xcode installed.
Make sure that you follow Fetching HTTPS pages with Zyte Smart Proxy Manager to install proper certificate in order to request pages with https.
Create a new
macOS
Project and selectApplication > Command Line Tool
.Copy entire
Sample Code
given below and paste inmain.m
.Replace
<SPM-APIKEY>
with Zyte Smart Proxy Manager API Key.Press
Command + R
to run the program or SelectProduct > Run
from the Menu bar.The output can be found on Console. Active Console by pressing
Shift + Command + C
or by SelectingView > Debug Area > Activate Console
from the Menu bar.
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
// Replace <SPM-APIKEY> with Zyte Smart Proxy Manager API Key
NSString *username = @"<SPM-APIKEY>";
NSString *password = @"";
NSString *authString = [NSString stringWithFormat:@"%@:%@",
username,
password];
// Convert authString to an NSData instance
NSData *authData = [authString dataUsingEncoding:NSUTF8StringEncoding];
// Build the header string with base64 encoded data
NSString *authHeader = [NSString stringWithFormat: @"Basic %@",
[authData base64EncodedStringWithOptions:0]];
// Building session configuration with proxy information
NSString* proxyHost = @"proxy.zyte.com";
NSNumber* proxyPort = [NSNumber numberWithInt: 8011];
NSDictionary *proxyDict = @{
@"HTTPEnable" : [NSNumber numberWithInt:1],
(NSString *)kCFNetworkProxiesHTTPProxy : proxyHost,
(NSString *)kCFNetworkProxiesHTTPPort : proxyPort,
@"HTTPSEnable" : [NSNumber numberWithInt:1],
(NSString *)kCFNetworkProxiesHTTPSProxy : proxyHost,
(NSString *)kCFNetworkProxiesHTTPSPort : proxyPort,
};
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
configuration.connectionProxyDictionary = proxyDict;
[configuration setHTTPAdditionalHeaders:@{@"Proxy-Authorization": authHeader}];
// Create a NSURLSession with the proxy-aware configuration
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
// Setting URL to request
NSURL *url = [NSURL URLWithString:@"https://toscrape.com"];
// Dispatch the request on the custom configured session
NSURLSessionDataTask *dataTask = [session dataTaskWithURL: url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"Response: %@",response);
NSLog(@"Data: %@",data);
NSLog(@"Error: %@",error);
CFRunLoopStop(CFRunLoopGetCurrent());
exit(EXIT_SUCCESS);
}];
[dataTask resume];
CFRunLoopRun();
return 0;
}