How to get the user agent on iOS?

后端 未结 6 2007
天涯浪人
天涯浪人 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条回答
  •  时光取名叫无心
    2020-12-14 20:44

    A simpler way to ascertain the user agent in iOS is to get it directly from a UIWebView using the accepted answer to this SO post.But this way has two disadvantages:
    1、UIWebView's first allocation may take too much time in initializing webview context.
    2、the code must be executed in main thread. This may stuck main thread.
    If you know the tricks of how to use private methods while avoiding the refusal of App Store Review.
    You can try the following code:

    
        #define CALL_PRIVATE_INSTANCEMETHOD(x,sel,q)\
        {\
        SEL selector = NSSelectorFromString([NSString stringWithFormat:@"%@",@#sel]);\
        if ([x respondsToSelector:selector]) {\
        _Pragma("clang diagnostic push")\
        _Pragma("clang diagnostic ignored \"-Warc-performSelector-leaks\"")\
        q=[x performSelector:selector];\
        _Pragma("clang diagnostic pop")\
        }\
        }\
    
        #define CALL_PRIVATE_CLASSMETHOD_ONEPARAM(x,sel,p,q)\
        {\
        SEL selector = NSSelectorFromString([NSString stringWithFormat:@"_%@:",@#sel]);\
        if ([x respondsToSelector:selector]) {\
        _Pragma("clang diagnostic push")\
        _Pragma("clang diagnostic ignored \"-Warc-performSelector-leaks\"")\
        q=[x performSelector:selector withObject:p];\
        _Pragma("clang diagnostic pop")\
        }\
        }\
    
        + (NSString *)standardUserAgent{
            NSString *buildVersion = nil;
            CALL_PRIVATE_INSTANCEMETHOD([UIDevice currentDevice], buildVersion,buildVersion);
    
            Class webViewCls = NSClassFromString([NSString stringWithFormat:@"%@%@",@"Web",@"View"]);
            NSString *standardUA = nil;
            NSString *versions = [NSString stringWithFormat:@"Mobile/%@",buildVersion];
            CALL_PRIVATE_CLASSMETHOD_ONEPARAM(webViewCls, standardUserAgentWithApplicationName,versions,standardUA);    
            return standardUA;
        }
    
    

提交回复
热议问题