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傳輸協議許可

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章