37

I'm using a C# asp.net website.

How can I check if the user using ipad or iphone? How can I check the platform?

For example, if the user enter the website from ipad I'd like to display"Hello ipad user"

Nathan Koop
  • 24,803
  • 25
  • 90
  • 125
avnic
  • 3,241
  • 8
  • 37
  • 46
  • 2
    Can you be more specific? Are you writing a C# application with MonoTouch for deployment to these devices? Are you writing a C# ASP .NET website which will be accessed by these devices? – David Mar 01 '11 at 14:01
  • I gues it is not a C# application but a C# webserver (ASP?) You should check the UserAgent – RvdK Mar 01 '11 at 14:02
  • Yes it is c# asp.net web – avnic Mar 01 '11 at 14:10
  • 1
    Wikipedia has an introduction to UserAgent here: http://en.wikipedia.org/wiki/User_agent. – Mike Chess Mar 01 '11 at 14:16

9 Answers9

73

UPDATE on 17-07-2020: it looks like Apple removed the word iPad and now use Macintosh instead

UPDATE: Since the iPad user agent contains the word iPhone as @Rob Hruska mentioned:

Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10

and iPhone user agent is something like this:

Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7

it would be correct to check for the word iPhone; or iPad; to identify the device:

var userAgent = HttpContext.Current.Request.UserAgent.ToLower();
if (userAgent.Contains("iphone;"))
{
    // iPhone
}
else if (userAgent.Contains("ipad;") || userAgent.Contains("macintosh;"))
{
    // iPad
}
else
{
    // Think Different ;)
}
Oleks
  • 31,955
  • 11
  • 77
  • 132
  • 2
    this solution is actually ok, works for me, wonder why this is not the selected answer... *hehe* i merely copy and pasted and 'Alex' this helped.. Thanks! :) – visual Feb 23 '12 at 08:10
  • 1
    Yo Alex, it helped me too. +1. – Jack Jul 12 '12 at 14:18
  • 5
    Won't this identify iPads as iPhones, since the [iPad user agent](http://stackoverflow.com/a/2248420/29995) contains `... CPU iPhone ...`? – Rob Hruska Jan 03 '13 at 20:54
  • 7
    Need to check for iPad *before* iPhone since iPad also contains iPhone, or will always get iPhone as answer. –  Jan 16 '13 at 20:14
  • 1
    @Ken-AbdiasSoftware, need to check for `iPhone;` or `iPad`. The order doesn't matter. – Oleks Jan 17 '13 at 10:13
  • @Alex - This will return a lot of Windows phones as iPhone == true because they have "like iPhone" in the user agent. See my full answer below. – bytedev Dec 07 '15 at 16:30
  • Worth mentioning that iPod touch will have the string "iPod" in the user agent. – bytedev Dec 07 '15 at 16:33
  • @Alex this will id Windows phones as iPhones. See my answer below. – bytedev Aug 30 '16 at 15:55
  • @nashwan: thanks for pointing out, but it should work since I'm looking for a keyword with a semicolon `;` which win phones don't have yet in their user agent string. – Oleks Aug 30 '16 at 16:55
  • @Alex fair enough, though I doubt Apple will ever put "like" as a prefix to "iPhone" ;-) – bytedev Aug 31 '16 at 10:20
  • This answer is no longer correct, since iPadOS removed the "iPad" from the user agent string by default. `Settings -> Safari -> Request Desktop Website -> All websites` is now on by default. – PerpetualStudent Jul 17 '20 at 11:18
  • It seems that `macintosh` is case sensitive. For me this worked: `if ((RequestingUserAgent.Contains("(iPhone;") || RequestingUserAgent.Contains("Macintosh;") || RequestingUserAgent.Contains("(iPad;"))` – Rahul Sharma Jun 22 '23 at 11:55
22

For iPad user agent is something like:

Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10

and for iPhone its somthing like:

Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3

Any many more depending on the version and wheather its iPhone 3 or 4

so better just do a substring search for iPhone and iPad as suggested by another answer

Shekhar_Pro
  • 18,056
  • 9
  • 55
  • 79
  • Searching for "iPhone" will also id Windows phones as iPhones. See my answer below. – bytedev Aug 30 '16 at 15:55
  • 1
    New iPad looks like Macintosh in their User Agents. See https://getpolarized.io/2019/12/21/Apple-Lying-About-User-Agent-in-iPad-Pro.html – malex Jan 21 '20 at 12:13
  • This answer is no longer correct, since iPadOS removed the "iPad" from the user agent string by default. `Settings -> Safari -> Request Desktop Website -> All websites` is now on by default. – PerpetualStudent Jul 15 '20 at 12:27
5

The user-agent for these devices includes "iPod", "iPad" or "IPhone" as appropriate. Note that there are several user agents in play, so an exact match is unwise - but have a look from your device at http://whatsmyuseragent.com

So check the user-agent in the headers.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
4

I would try WURFL first http://wurfl.sourceforge.net/

They have .NET API and Very good code samples. http://wurfl.sourceforge.net/dotnet_index.php

The class that will help you is called WURFLManager and has the following methods:

enter image description here

Use WURFL http://wurfl.sourceforge.net/dotnet_index.php

If you using asp.net mvc you can use an ActionFilter

public class MobileActionFilterAttribute : ActionFilterAttribute
{
    // The WURFL database contains information about a huge number of devices and mobile browsers.
    // http://wurfl.sourceforge.net/
    // http://wurfl.sourceforge.net/dotnet_index.php
    // http://wurfl.sourceforge.net/help_doc.php

    private static readonly IWURFLManager WurflManager;

    static MobileActionFilterAttribute ()
    {
        IWURFLConfigurer configurer = new ApplicationConfigurer();
        WurflManager = WURFLManagerBuilder.Build(configurer);
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        HttpRequestBase request = filterContext.RequestContext.HttpContext.Request;

        // We don't have ARR server for dev environment, so we still need to check to see if the current domain name is the mobile site.
        if (request.Url.AbsoluteUri.StartsWith(SiteConfiguration.Current.MobileSiteAddress, StringComparison.OrdinalIgnoreCase))
        {
            return;
        }

        // Creates a WURFLRequest object from an ASP.NET HttpRequest object
        WURFLRequest wurflRequest = WURFLRequestFactory.CreateRequest(HttpContext.Current.Request);

        // Indicates whether the current user agent string refers to a desktop agent.
        if (wurflRequest.IsDesktopRequest)
            return;

        // Get the information about the device
        IDevice deviceInfo = WurflManager.GetDeviceForRequest(wurflRequest);

        // Tells you if a device is a tablet computer (iPad and similar, regardless of OS)
        bool isTablet = string.Equals(deviceInfo.GetCapability("is_tablet") ?? string.Empty, "true", StringComparison.OrdinalIgnoreCase);

        if (isTablet)
        {
            // so we don't show the mobile site for iPad.
            return;
        }

        // Indicates whether the current user agent string refers to a mobile device.
        bool isMobileRequest = wurflRequest.IsMobileRequest;

        // Tells you if a device is wireless or not. Specifically a mobile phone or a PDA are considered wireless devices, a desktop PC or a laptop are not
        bool isWirelessDevice = string.Equals(deviceInfo.GetCapability("is_wireless_device") ?? string.Empty, "true", StringComparison.InvariantCultureIgnoreCase);

        if (isMobileRequest && isWirelessDevice)
        {
            // we can redirect to the mobile site!
            filterContext.Result = new RedirectResult(SiteConfiguration.Current.MobileSiteAddress);
        }
    }
}

There is also 51Degrees.Mobi Steve Sanderson has covered how to do this on his blog http://blog.stevensanderson.com/2010/12/17/using-51degreesmobi-foundation-for-accurate-mobile-browser-detection-on-aspnet-mvc-3/

51Degrees.Mobi Foundation is an open source .NET project that enhances Request.Browser so it gets its information from Wireless Universal Resource File (WURFL) – one of the most comprehensive and up-to-date databases of mobile device information. The great news is that 51Degrees.Mobi Foundation is now available as a NuGet package, so it’s incredibly easy to install and update.

superlogical
  • 14,332
  • 9
  • 66
  • 76
4

you can do it by getting the UserAgent

string ua = Request.UserAgent;
if (ua != null && (ua.Contains("iPhone") || ua.Contains("iPad")))
{
...
...
...
}
Bala R
  • 107,317
  • 23
  • 199
  • 210
3

Be careful of Windows phones! For some weird reason lots of Windows phones say "like iPhone" in the user agent. So you want to check:

public bool IsIPhone
{
    get
    {
        if (!UserAgent.ToUpper().Contains("LIKE IPHONE"))
        {
            return UserAgent.ToUpper().Contains("IPHONE");
        }
        return false;
    }
}

Example Windows phone user agent (from Lumia 735):

"Mozilla/5.0 (Mobile; Windows Phone 8.1; Android 4.0; ARM; Trident/7.0; Touch; rv:11.0; IEMobile/11.0; NOKIA; Lumia 735) like iPhone OS 7_0_3 Mac OS X AppleWebKit/537 (KHTML, like Gecko) Mobile Safari/537"

bytedev
  • 8,252
  • 4
  • 48
  • 56
2

From iOS 13 the user agent changed to Mac OS, for example:

Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0 Safari/605.1.15

zvi
  • 3,677
  • 2
  • 30
  • 48
0
private static final Pattern IPHONE_AGENT = Pattern.compile(".*iPad.*|.*iPhone.*|.*iPod.*");    

String userAgent = request.getHeader("User-Agent");
if (userAgent != null && IPHONE_AGENT.matcher(userAgent).matches()) {
    // do something
}
splashout
  • 537
  • 5
  • 11
0

you can get client OS data from Request.UserAgent get OS name and OS version.

  public static string GetClientOS(string ua, string platform)
    {

        if (ua.Contains("Android"))
            return string.Format("Android {0}", GetMobileVersion(ua, "Android"));

        if (ua.Contains("iPad"))
            return string.Format("iPad OS {0}", GetMobileVersion(ua, "OS"));

        if (ua.Contains("iPhone"))
            return string.Format("iPhone OS {0}", GetMobileVersion(ua, "OS"));

        if (ua.Contains("Linux") && ua.Contains("KFAPWI"))
            return "Kindle Fire";

        if (ua.Contains("RIM Tablet") || (ua.Contains("BB") && ua.Contains("Mobile")))
            return "Black Berry";

        if (ua.Contains("Windows Phone"))
            return string.Format("Windows Phone {0}", GetMobileVersion(ua, "Windows Phone"));

        if (ua.Contains("Mac OS"))
            return "Mac OS";

        if (ua.Contains("Windows NT 5.1") || ua.Contains("Windows NT 5.2"))
            return "Windows XP";

        if (ua.Contains("Windows NT 6.0"))
            return "Windows Vista";

        if (ua.Contains("Windows NT 6.1"))
            return "Windows 7";

        if (ua.Contains("Windows NT 6.2"))
            return "Windows 8";

        if (ua.Contains("Windows NT 6.3"))
            return "Windows 8.1";

        if (ua.Contains("Windows NT 10"))
            return "Windows 10";

        return  platform + (ua.Contains("Mobile") ? " Mobile " : "");
    }

    public static string GetMobileVersion(string userAgent, string device)
    {
        var temp = userAgent.Substring(userAgent.IndexOf(device) + device.Length).TrimStart();
        var version = string.Empty;

        foreach (var character in temp)
        {
            var validCharacter = false;
            int test = 0;

            if (int.TryParse(character.ToString(), out test))
            {
                version += character;
                validCharacter = true;
            }

            if (character == '.' || character == '_')
            {
                version += '.';
                validCharacter = true;
            }

            if (validCharacter == false)
                break;
        }

        return version;
    }
AmirNorouzpour
  • 1,119
  • 1
  • 11
  • 26