ios 获取外网ip

今天在网上找了一个获取外网地址的方法无奈,Data的initcontentsOfURL一直不好使,然后查询了一些资料得到了一个能使用的方法。下面贴代码。

/// 获取外网ip

///

/// - Returns: 外网ip

func getIpinfo() ->String?

{

/** 这是ip查询网址 */

let urlStr = "http://ip.taobao.com/service/getIpInfo.php?ip=myip"

/** 编码为下面转换数据做准备 */

let strEncoding = urlStr.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)

if strEncoding != nil {

do{

let data = try Data.init(contentsOf: URL.init(string: strEncoding!)!)

do

{

/** 解析data */

if let resultDic = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves) as? [String:Any]

{

/** 打印结果 这边数据比较多类似以下数据 */

/** {

code = 0;

data =    {

area = "\U534e\U4e1c";

"area_id" = 300000;

city = "\U4e0a\U6d77\U5e02";

"city_id" = 310100;

country = "\U4e2d\U56fd";

"country_id" = CN;

county = "";

"county_id" = "-1";

ip = "139.226.164.200";

isp = "\U8054\U901a";

"isp_id" = 100026;

region = "\U4e0a\U6d77\U5e02";

"region_id" = 310000;

};

} */

print(resultDic)

/** 用guard逻辑稍微清晰点  */

guard let resultCode = resultDic["code"] as? Int  else

{

print("data error")

return nil;

}

guard resultCode == 0 else

{

print("code error")

return nil

}

guard let dataDic = resultDic["data"] as? [String:Any] else

{

print("dic info error")

return nil;

}

guard let ip = dataDic["ip"] as? String else

{

print("ip error")

return nil;

}

/** 得到最终结果 */

return ip

}

}

catch

{

print(error.localizedDescription)

}

}

catch

{

print(error.localizedDescription)

}

}

return nil

}

比较喜欢swift的机制把不确定因素在代码界面排除支持swift

忘了补充下 记得在info.plist文件中加http传输协议许可

猜你喜欢

转载自blog.csdn.net/asuno_1/article/details/80527846