iOS如何仅通过蜂窝网络正确发送请求

iOS如何仅通过蜂窝网络正确发送请求,ios,networking,Ios,Networking,我的问题显然是两种情况: (1) 仅通过wifi发送请求URL1 (2) 仅通过手机发送请求URL2 我知道可访问性实用程序(苹果的代码和AFNetworking/Alamofire代码)和AllowCellularAccess属性(在NSMutableURLRequest和NSURLSessionConfiguration中) 但这些只解决了情况(1)(因为我将allowscellaraccess设置为NO)。 情况(2)无法确保,因为请求可以通过蜂窝或wifi(如果可用)运行。即使我仅通

我的问题显然是两种情况:

  • (1) 仅通过wifi发送请求URL1
  • (2) 仅通过手机发送请求URL2
我知道
可访问性
实用程序(苹果的代码和AFNetworking/Alamofire代码)和
AllowCellularAccess
属性(在NSMutableURLRequest和NSURLSessionConfiguration中)

但这些只解决了情况(1)(因为我将
allowscellaraccess
设置为NO)。 情况(2)无法确保,因为请求可以通过蜂窝或wifi(如果可用)运行。即使我仅通过蜂窝网络的可达性检查状态,仍有一些异常情况,如本文档所述

有没有更好的办法确保只使用蜂窝网络?欢迎任何客人。Object-C和Swift都受到欢迎

提前感谢

如果满足以下条件,您可以在IP_绑定的套接字中执行此操作:
  • 使用“ifaddrs.h”中包含的“getifaddrs”获取接口地址:
  • 然后您将看到如下输出:
    lo0;127.0.0.1;255.0.0.0;127.0.0.1
    pdp_ip0;10.9.163.185;255.255.255.255;10.9.163.185
    en0;10.0.0.6;255.255.0.0;10.0.255.255

    (“pdp_ip0”指cellualr接口)

  • 使用“net/if.h”中的“if_nametoindex”和“sys/socket.h”中的“setsockopt”通过指定的接口发送消息

  • 然后连接套接字,您将看到您已通过蜂窝接口连接服务器

    然后连接套接字?这还不清楚。你的意思是我们需要调用一些HTTP请求后请解释更多关于这个的信息!你找到解决办法了吗?
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    NSInteger success = getifaddrs(&interfaces);
    if (success == 0) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while(temp_addr != NULL) {
            if(temp_addr->ifa_addr->sa_family == AF_INET) {
                // Get NSString from C String
                NSString* ifaName = [NSString stringWithUTF8String:temp_addr->ifa_name];
                NSString* address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *) temp_addr->ifa_addr)->sin_addr)];
                NSString* mask = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *) temp_addr->ifa_netmask)->sin_addr)];
                NSString* gateway = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *) temp_addr->ifa_dstaddr)->sin_addr)];
                NSLog(@"%@;%@;%@;%@",ifaName,address,mask,gateway);
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
    
    int s = socket(AF_INET, SOCK_STREAM, 0); 
    int index = if_nametoindex( "pdp_ip0");
    int suc = setsockopt(s, IPPROTO_IP, IP_BOUND_IF, &index, sizeof(index));