iOS Objective-C 获取公网 IP 地址:简单示例代码
在 iOS 中,可以通过访问一个公开的 IP 地址查询接口来获取自己当前的公网 IP。以下是一个使用 Objective-C 的示例代码:
#import <Foundation/Foundation.h>
@interface MyIPFetcher : NSObject <NSURLSessionDelegate>
@property (nonatomic, copy) void (^completionHandler)(NSString *);
- (void)fetchPublicIP;
@end
@implementation MyIPFetcher
- (void)fetchPublicIP {
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:'https://api.ipify.org?format=json'];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog('Error: %@', error);
self.completionHandler(nil);
return;
}
NSError *jsonError;
NSDictionary *ipInfo = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonError];
if (jsonError) {
NSLog('JSON Error: %@', jsonError);
self.completionHandler(nil);
return;
}
NSString *publicIP = ipInfo['ip'];
self.completionHandler(publicIP);
}];
[dataTask resume];
}
@end
// Usage
MyIPFetcher *ipFetcher = [[MyIPFetcher alloc] init];
[ipFetcher fetchPublicIP];
[ipFetcher setCompletionHandler:^(NSString *ip) {
NSLog('My Public IP: %@', ip);
}];
上述代码使用 NSURLSession 发送 HTTP 请求到 https://api.ipify.org?format=json,该接口会返回一个 JSON 响应,其中包含当前的公网 IP 地址。在回调中,你可以获取到这个公网 IP 地址并进行后续处理。
原文地址: https://www.cveoy.top/t/topic/qjiw 著作权归作者所有。请勿转载和采集!