How to get the user agent on iOS?

后端 未结 6 2014
天涯浪人
天涯浪人 2020-12-14 19:59

Is there a way on iOS to get the user agent of the device? I don\'t want to hard code it since I need the user agent for all devices and I need to append the user agent to a

6条回答
  •  Happy的楠姐
    2020-12-14 20:49

    Mobile application in every request must send his User-Agent header with build version and device information

    User agent configuration info

    So, user agent should be like:

    User-Agent: /version () ()

    For iOS:

    User-Agent: (; ; iOS/) CFNetwork/ Darwin/

    How to get each of the components?

    1. Headers Key - u can hardcode or use some constant values
    2. AppName and version - grab from Info.plist

      let infoPlist = try? PListFile()
      let appName = infoPlist.data.bundleName
      let version = infoPlist.data.versionNumber
      let build = infoPlist.data.buildNumber
      
    3. Info about Device

    modelName - you can obtain like described here

        let modelName = UIDevice.current.modelName
    

    other components:

        let platform = UIDevice.current.systemName
        let operationSystemVersion = ProcessInfo.processInfo.operatingSystemVersionString
    
    1. CFNetwork version

      static var cfNetworkVersion: String? {
        guard
          let bundle = Bundle(identifier: "com.apple.CFNetwork"),
           let versionAny = bundle.infoDictionary?[kCFBundleVersionKey as String],
           let version = versionAny as? String
            else { return nil }
        return version
      }
      

    from here

    1. Darwin Version

       var systemInfo = utsname()
       uname(&systemInfo)
       let machineMirror = Mirror(reflecting: systemInfo.release)
       let darvinVersionString = machineMirror.children.reduce("") { identifier, element in
         guard let value = element.value as? Int8,
           value != 0 else {
             return identifier
         }
      
         return identifier + String(UnicodeScalar(UInt8(value)))
       }
      

    from here

    Result:

    MyApp/1.8.199 (iOS; iPhone XS; Version 13.3 (Build 17C45)) CFNetwork/1121.2.1 Darvin/19.3.0

提交回复
热议问题