iOS 獲取裝置uuid,公網ip,手機ip等資訊

陳重陽發表於2018-04-11

最近公司app需要新增獲取使用者資訊的新功能。將這些 功能寫下來,以備不時之需。

獲取手機uuid

+ (String *)getUUID 
{  
    return [[[UIDevice currentDevice] identifierForVendor] UUIDString];

}

獲取作業系統版本

+ (float)getIOSVersion  
{  
    return [[[UIDevice currentDevice] systemVersion] floatValue];  
}  

獲取位置資訊

設定請求訪問資訊

<key>NSLocationWhenInUseUsageDescription</key>
<string>when</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>always</string>

完整程式碼

#import <CoreLocation/CoreLocation.h>
@interface MainViewController ()<CLLocationManagerDelegate>
{
    CLLocationManager *locationmanager;//定位服務
    NSString *currentCity;//當前城市
    NSString *strlatitude;//經度
    NSString *strlongitude;//緯度
}
@end

@implementation MainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self startLocation];
    // Do any additional setup after loading the view.
}

//開始定位
- (void)startLocation {
    if ([CLLocationManager locationServicesEnabled]) {
        //        CLog(@"--------開始定位");
        self.locationManager = [[CLLocationManager alloc]init];
        self.locationManager.delegate = self;
        //控制定位精度,越高耗電量越大
        self.locationManager.desiredAccuracy = kCLLocationAccuracyKilometer;
        // 總是授權
        [self.locationManager requestAlwaysAuthorization];
        self.locationManager.distanceFilter = 10.0f;
        [self.locationManager requestAlwaysAuthorization];
        [self.locationManager startUpdatingLocation];
    }
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    if ([error code] == kCLErrorDenied) {
        CLog(@"訪問被拒絕");
    }
    if ([error code] == kCLErrorLocationUnknown) {
        CLog(@"無法獲取位置資訊");
    }
}

//定位代理經緯度回撥
#pragma mark 定位成功後則執行此代理方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    [locationmanager stopUpdatingHeading];
    //舊址
    CLLocation *currentLocation = [locations lastObject];
    CLGeocoder *geoCoder = [[CLGeocoder alloc]init];
    //列印當前的經度與緯度
    NSLog(@"%f,%f",currentLocation.coordinate.latitude,currentLocation.coordinate.longitude);

    //反地理編碼
    [geoCoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (placemarks.count > 0) {
            CLPlacemark *placeMark = placemarks[0];
            currentCity = placeMark.locality;
            if (!currentCity) {
                currentCity = @"無法定位當前城市";
            }

            /*看需求定義一個全域性變數來接收賦值*/
            NSLog(@"----%@",placeMark.country);//當前國家
            NSLog(@"%@",currentCity);//當前的城市
//            NSLog(@"%@",placeMark.subLocality);//當前的位置
//            NSLog(@"%@",placeMark.thoroughfare);//當前街道
//            NSLog(@"%@",placeMark.name);//具體地址

        }
    }];

}

獲取公網ip

+(NSString *)deviceWANIPAddress  
{  
    NSURL *ipURL = [NSURL URLWithString:@"http://ip.taobao.com/service/getIpInfo.php?ip=myip"];  
    NSData *data = [NSData dataWithContentsOfURL:ipURL];  
    NSDictionary *ipDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];?  
    NSString *ipStr = nil;  
    if (ipDic && [ipDic[@"code"] integerValue] == 0) { //獲取成功  
        ipStr = ipDic[@"data"][@"ip"];  
    }  
    return (ipStr ? ipStr : @"");  
}  

獲取當前時間

獲取當前時間

- (NSString *)currentDateStr{
    NSDate *currentDate = [NSDate date];//獲取當前時間,日期
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];// 建立一個時間格式化物件
    [dateFormatter setDateFormat:@"YYYY/MM/dd hh:mm:ss SS "];//設定時間格式,這裡可以設定成自己需要的格式
    NSString *dateString = [dateFormatter stringFromDate:currentDate];//將時間轉化成字串
    return dateString;
}

獲取當前時間戳

//獲取當前時間戳
- (NSString *)currentTimeStr{
    NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];//獲取當前時間0秒後的時間
    NSTimeInterval time=[date timeIntervalSince1970]*1000;// *1000 是精確到毫秒,不乘就是精確到秒
    NSString *timeString = [NSString stringWithFormat:@"%.0f", time];
    return timeString;
}

獲取移動端ip

需要的標頭檔案

//IP地址需求庫  
#import <sys/socket.h>  
#import <sys/sockio.h>  
#import <sys/ioctl.h>  
#import <net/if.h>  
#import <arpa/inet.h>  

獲取ip地址

//獲取裝置IP地址  
+ (NSString *)getDeviceIPAddresses  
{  
    int sockfd = socket(AF_INET,SOCK_DGRAM, 0);  
    // if (sockfd <</span> 0) return nil; //這句報錯,由於轉載的,不太懂,註釋掉無影響,懂的大神歡迎指導  
    NSMutableArray *ips = [NSMutableArray array];  

    int BUFFERSIZE =4096;  

    struct ifconf ifc;  

    char buffer[BUFFERSIZE], *ptr, lastname[IFNAMSIZ], *cptr;  

    struct ifreq *ifr, ifrcopy;  

    ifc.ifc_len = BUFFERSIZE;  

    ifc.ifc_buf = buffer;  

    if (ioctl(sockfd,SIOCGIFCONF, &ifc) >= 0){  

        for (ptr = buffer; ptr < buffer + ifc.ifc_len; ){  

            ifr = (struct ifreq *)ptr;  

            int len =sizeof(struct sockaddr);  

            if (ifr->ifr_addr.sa_len > len) {  
                len = ifr->ifr_addr.sa_len;  
            }  

            ptr += sizeof(ifr->ifr_name) + len;  

            if (ifr->ifr_addr.sa_family !=AF_INET) continue;  

            if ((cptr = (charchar *)strchr(ifr->ifr_name,':')) != NULL) *cptr =0;  

            if (strncmp(lastname, ifr->ifr_name,IFNAMSIZ) == 0)continue;  

            memcpy(lastname, ifr->ifr_name,IFNAMSIZ);  

            ifrcopy = *ifr;  

            ioctl(sockfd,SIOCGIFFLAGS, &ifrcopy);  

            if ((ifrcopy.ifr_flags &IFF_UP) == 0)continue;  

            NSString *ip = [NSString stringWithFormat:@"%s",inet_ntoa(((struct sockaddr_in *)&ifr->ifr_addr)->sin_addr)];  
            [ips addObject:ip];  
        }  
    }  
    close(sockfd);  

    NSString *deviceIP =@"";  

    for (int i=0; i < ips.count; i++){  
        if (ips.count >0){  
            deviceIP = [NSString stringWithFormat:@"%@",ips.lastObject];  
        }  
    }  

    return deviceIP;  
}  

以上方法沒有進行測試,使用時需要自己測試。

最後給出自己的個人部落格

相關文章