[Reachability] Fix startup crash + update sample

This commit is contained in:
Oleg Demchenko 2015-09-10 11:37:25 -03:00
Родитель 1b316ce381
Коммит d75b9c3f64
12 изменённых файлов: 535 добавлений и 673 удалений

Просмотреть файл

@ -1,170 +1,10 @@
using System; using Foundation;
using CoreGraphics;
using Foundation;
using UIKit; using UIKit;
namespace reachability namespace Reachability {
{ [Register ("AppDelegate")]
public partial class ReachabilityAppDelegate : UIApplicationDelegate public class AppDelegate : UIApplicationDelegate {
{ public override UIWindow Window { get; set; }
UITableView tableView;
NetworkStatus remoteHostStatus, internetStatus, localWifiStatus;
static void Main (string[] args)
{
UIApplication.Main (args, null, (string)null);
}
public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions)
{
AddTable ();
UpdateStatus ();
Reachability.ReachabilityChanged += (object sender, EventArgs e) => {
UpdateStatus ();
};
window.MakeKeyAndVisible ();
return true;
}
void UpdateStatus ()
{
remoteHostStatus = Reachability.RemoteHostStatus ();
internetStatus = Reachability.InternetConnectionStatus ();
localWifiStatus = Reachability.LocalWifiConnectionStatus ();
tableView.ReloadData ();
}
void AddTable ()
{
CGRect tableFrame = UIScreen.MainScreen.ApplicationFrame;
tableView = new UITableView (tableFrame, UITableViewStyle.Grouped) {
AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight,
RowHeight = 44.0f,
SeparatorStyle = UITableViewCellSeparatorStyle.None,
SectionHeaderHeight = 28.0f,
ScrollEnabled = false,
Source = new DataSource (this),
};
contentView.InsertSubviewBelow (tableView, summaryLabel);
contentView.BringSubviewToFront (summaryLabel);
tableView.ReloadData ();
}
class DataSource : UITableViewSource
{
ReachabilityAppDelegate parent;
UIImage imageCarrier, imageWiFi, imageStop;
public DataSource (ReachabilityAppDelegate parent)
{
imageCarrier = UIImage.FromFile ("WWAN5.png");
imageWiFi = UIImage.FromFile ("Airport.png");
imageStop = UIImage.FromFile ("stop-32.png");
this.parent = parent;
}
public override NSIndexPath WillSelectRow (UITableView view, NSIndexPath index)
{
return null;
}
public override nint RowsInSection (UITableView view, nint section)
{
return 1;
}
public override nint NumberOfSections (UITableView view)
{
return 3;
}
public override string TitleForHeader (UITableView view, nint section)
{
switch (section) {
case 0:
return Reachability.HostName;
case 1:
return "Access to internet hosts";
case 2:
return "Access to Local Bonjour Hosts";
default:
return "Unknown";
}
}
static NSString ReachabilityTableCellIdentifier = new NSString ("ReachabilityTableCell");
public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
{
var cell = tableView.DequeueReusableCell (ReachabilityTableCellIdentifier);
if (cell == null) {
cell = new UITableViewCell (UITableViewCellStyle.Default, ReachabilityTableCellIdentifier);
var label = cell.TextLabel;
label.Font = UIFont.SystemFontOfSize (12f);
label.TextColor = UIColor.DarkGray;
label.TextAlignment = UITextAlignment.Left;
}
var row = indexPath.Row;
string text = "";
UIImage image = null;
switch (indexPath.Section) {
case 0:
switch (parent.remoteHostStatus) {
case NetworkStatus.NotReachable:
text = "Cannot connect to remote host";
image = imageStop;
break;
case NetworkStatus.ReachableViaCarrierDataNetwork:
text = "Reachable via data carrier network";
image = imageCarrier;
break;
case NetworkStatus.ReachableViaWiFiNetwork:
text = "Reachable via WiFi network";
image = imageWiFi;
break;
}
break;
case 1:
switch (parent.internetStatus) {
case NetworkStatus.NotReachable:
text = "Access not available";
image = imageStop;
break;
case NetworkStatus.ReachableViaCarrierDataNetwork:
text = "Available via data carrier network";
image = imageCarrier;
break;
case NetworkStatus.ReachableViaWiFiNetwork:
text = "Available via WiFi network";
image = imageWiFi;
break;
}
break;
case 2:
switch (parent.localWifiStatus) {
case NetworkStatus.NotReachable:
text = "Access not available";
image = imageStop;
break;
case NetworkStatus.ReachableViaWiFiNetwork:
text = "Available via WiFi network";
image = imageWiFi;
break;
}
break;
}
cell.TextLabel.Text = text;
cell.ImageView.Image = image;
return cell;
}
}
} }
} }

Просмотреть файл

@ -29,5 +29,7 @@
<array> <array>
<string>UIInterfaceOrientationPortrait</string> <string>UIInterfaceOrientationPortrait</string>
</array> </array>
<key>UIMainStoryboardFile</key>
<string>Main</string>
</dict> </dict>
</plist> </plist>

Просмотреть файл

@ -0,0 +1,14 @@
using UIKit;
namespace Reachability {
public class Application {
// This is the main entry point of the application.
static void Main (string[] args)
{
// if you want to use a different Application Delegate class from "AppDelegate"
// you can specify it here.
UIApplication.Main (args, null, "AppDelegate");
}
}
}

Просмотреть файл

@ -0,0 +1,57 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="8187.4" systemVersion="15A178w" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" initialViewController="G6t-Sy-zaY">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="8151.3"/>
</dependencies>
<scenes>
<!--Root View Controller-->
<scene sceneID="AaP-65-3tI">
<objects>
<tableViewController id="uYg-Wb-NE8" customClass="MainViewController" sceneMemberID="viewController">
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="44" sectionHeaderHeight="28" sectionFooterHeight="28" id="bpy-jb-hsL">
<rect key="frame" x="0.0" y="0.0" width="320" height="568"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<animations/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/>
<prototypes>
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" indentationWidth="10" id="V1L-rk-bW7">
<rect key="frame" x="0.0" y="92" width="320" height="44"/>
<autoresizingMask key="autoresizingMask"/>
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="V1L-rk-bW7" id="mEc-0D-cmu">
<rect key="frame" x="0.0" y="0.0" width="320" height="43.5"/>
<autoresizingMask key="autoresizingMask"/>
<animations/>
</tableViewCellContentView>
<animations/>
</tableViewCell>
</prototypes>
<connections>
<outlet property="dataSource" destination="uYg-Wb-NE8" id="UW0-nO-B63"/>
<outlet property="delegate" destination="uYg-Wb-NE8" id="SFR-fz-wuW"/>
</connections>
</tableView>
<navigationItem key="navigationItem" title="Root View Controller" id="WD6-LY-Wq6"/>
</tableViewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="WLN-0l-dYf" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="748" y="134"/>
</scene>
<!--Navigation Controller-->
<scene sceneID="rk5-AZ-VT1">
<objects>
<navigationController id="G6t-Sy-zaY" sceneMemberID="viewController">
<navigationBar key="navigationBar" contentMode="scaleToFill" id="AZi-ef-rH6">
<rect key="frame" x="0.0" y="0.0" width="320" height="44"/>
<autoresizingMask key="autoresizingMask"/>
<animations/>
</navigationBar>
<connections>
<segue destination="uYg-Wb-NE8" kind="relationship" relationship="rootViewController" id="FKX-Rz-4BI"/>
</connections>
</navigationController>
<placeholder placeholderIdentifier="IBFirstResponder" id="R6s-Lf-xV5" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="208" y="134"/>
</scene>
</scenes>
</document>

Просмотреть файл

@ -0,0 +1,135 @@
using System;
using UIKit;
using Foundation;
namespace Reachability {
public partial class MainViewController : UITableViewController {
const string ReachabilityTableCellIdentifier = "ReachabilityTableCell";
UIImage imageCarrier, imageWiFi, imageStop;
NetworkStatus remoteHostStatus, internetStatus, localWifiStatus;
public MainViewController (IntPtr handle) : base (handle)
{
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
UpdateStatus (null, null);
Reachability.ReachabilityChanged += UpdateStatus;
imageCarrier = UIImage.FromFile ("WWAN5.png");
imageWiFi = UIImage.FromFile ("Airport.png");
imageStop = UIImage.FromFile ("stop-32.png");
TableView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;
TableView.RowHeight = 44.0f;
TableView.SeparatorStyle = UITableViewCellSeparatorStyle.None;
TableView.SectionHeaderHeight = 28.0f;
TableView.ScrollEnabled = false;
}
public override NSIndexPath WillSelectRow (UITableView view, NSIndexPath index)
{
return null;
}
public override nint RowsInSection (UITableView view, nint section)
{
return 1;
}
public override nint NumberOfSections (UITableView view)
{
return 3;
}
public override string TitleForHeader (UITableView view, nint section)
{
switch (section) {
case 0:
return Reachability.HostName;
case 1:
return "Access to internet hosts";
case 2:
return "Access to Local Bonjour Hosts";
default:
return "Unknown";
}
}
public override UITableViewCell GetCell (UITableView tableView, Foundation.NSIndexPath indexPath)
{
var cell = tableView.DequeueReusableCell (ReachabilityTableCellIdentifier);
if (cell == null) {
cell = new UITableViewCell (UITableViewCellStyle.Default, ReachabilityTableCellIdentifier);
var label = cell.TextLabel;
label.Font = UIFont.SystemFontOfSize (12f);
label.TextColor = UIColor.DarkGray;
label.TextAlignment = UITextAlignment.Left;
}
string text = "";
UIImage image = null;
switch (indexPath.Section) {
case 0:
switch (remoteHostStatus) {
case NetworkStatus.NotReachable:
text = "Cannot connect to remote host";
image = imageStop;
break;
case NetworkStatus.ReachableViaCarrierDataNetwork:
text = "Reachable via data carrier network";
image = imageCarrier;
break;
case NetworkStatus.ReachableViaWiFiNetwork:
text = "Reachable via WiFi network";
image = imageWiFi;
break;
}
break;
case 1:
switch (internetStatus) {
case NetworkStatus.NotReachable:
text = "Access not available";
image = imageStop;
break;
case NetworkStatus.ReachableViaCarrierDataNetwork:
text = "Available via data carrier network";
image = imageCarrier;
break;
case NetworkStatus.ReachableViaWiFiNetwork:
text = "Available via WiFi network";
image = imageWiFi;
break;
}
break;
case 2:
switch (localWifiStatus) {
case NetworkStatus.NotReachable:
text = "Access not available";
image = imageStop;
break;
case NetworkStatus.ReachableViaWiFiNetwork:
text = "Available via WiFi network";
image = imageWiFi;
break;
}
break;
}
cell.TextLabel.Text = text;
cell.ImageView.Image = image;
return cell;
}
void UpdateStatus (object sender, EventArgs e)
{
remoteHostStatus = Reachability.RemoteHostStatus ();
internetStatus = Reachability.InternetConnectionStatus ();
localWifiStatus = Reachability.LocalWifiConnectionStatus ();
TableView.ReloadData ();
}
}
}

20
ReachabilitySample/MainViewController.designer.cs сгенерированный Normal file
Просмотреть файл

@ -0,0 +1,20 @@
// WARNING
//
// This file has been generated automatically by Xamarin Studio to store outlets and
// actions made in the UI designer. If it is removed, they will be lost.
// Manual changes to this file may not be handled correctly.
//
using Foundation;
using System.CodeDom.Compiler;
namespace Reachability
{
[Register ("MainViewController")]
partial class MainViewController
{
void ReleaseDesignerOutlets ()
{
}
}
}

Просмотреть файл

@ -1,276 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<archive type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="7.10">
<data>
<int key="IBDocument.SystemTarget">512</int>
<string key="IBDocument.SystemVersion">10B504</string>
<string key="IBDocument.InterfaceBuilderVersion">740</string>
<string key="IBDocument.AppKitVersion">1038.22</string>
<string key="IBDocument.HIToolboxVersion">457.00</string>
<object class="NSMutableDictionary" key="IBDocument.PluginVersions">
<string key="NS.key.0">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
<string key="NS.object.0">62</string>
</object>
<object class="NSMutableArray" key="IBDocument.EditedObjectIDs">
<bool key="EncodedWithXMLCoder">YES</bool>
<integer value="7"/>
</object>
<object class="NSArray" key="IBDocument.PluginDependencies">
<bool key="EncodedWithXMLCoder">YES</bool>
<string>com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
</object>
<object class="NSMutableDictionary" key="IBDocument.Metadata">
<bool key="EncodedWithXMLCoder">YES</bool>
<object class="NSArray" key="dict.sortedKeys" id="0">
<bool key="EncodedWithXMLCoder">YES</bool>
</object>
<object class="NSMutableArray" key="dict.values">
<bool key="EncodedWithXMLCoder">YES</bool>
</object>
</object>
<object class="NSMutableArray" key="IBDocument.RootObjects" id="1000">
<bool key="EncodedWithXMLCoder">YES</bool>
<object class="IBProxyObject" id="841351856">
<string key="IBProxiedObjectIdentifier">IBFilesOwner</string>
</object>
<object class="IBProxyObject" id="1071500409">
<string key="IBProxiedObjectIdentifier">IBFirstResponder</string>
</object>
<object class="IBUICustomObject" id="987256611"/>
<object class="IBUIWindow" id="380026005">
<reference key="NSNextResponder"/>
<int key="NSvFlags">1292</int>
<object class="NSMutableArray" key="NSSubviews">
<bool key="EncodedWithXMLCoder">YES</bool>
<object class="IBUIView" id="388289409">
<reference key="NSNextResponder" ref="380026005"/>
<int key="NSvFlags">1298</int>
<object class="NSMutableArray" key="NSSubviews">
<bool key="EncodedWithXMLCoder">YES</bool>
<object class="IBUILabel" id="1041619883">
<reference key="NSNextResponder" ref="388289409"/>
<int key="NSvFlags">1306</int>
<string key="NSFrame">{{0, 318}, {320, 106}}</string>
<reference key="NSSuperview" ref="388289409"/>
<bool key="IBUIOpaque">NO</bool>
<bool key="IBUIClipsSubviews">YES</bool>
<bool key="IBUIUserInteractionEnabled">NO</bool>
<string key="IBUIText"/>
<object class="NSColor" key="IBUITextColor">
<int key="NSColorSpace">1</int>
<bytes key="NSRGB">MSAwIDAAA</bytes>
</object>
<nil key="IBUIHighlightedColor"/>
<int key="IBUIBaselineAdjustment">1</int>
<bool key="IBUIAdjustsFontSizeToFit">NO</bool>
<float key="IBUIMinimumFontSize">14</float>
<int key="IBUINumberOfLines">0</int>
<int key="IBUITextAlignment">1</int>
</object>
</object>
<string key="NSFrameSize">{320, 480}</string>
<reference key="NSSuperview" ref="380026005"/>
<object class="NSColor" key="IBUIBackgroundColor">
<int key="NSColorSpace">3</int>
<bytes key="NSWhite">MQA</bytes>
<object class="NSColorSpace" key="NSCustomColorSpace">
<int key="NSID">2</int>
</object>
</object>
<bool key="IBUIClearsContextBeforeDrawing">NO</bool>
<bool key="IBUIUserInteractionEnabled">NO</bool>
</object>
</object>
<object class="NSPSMatrix" key="NSFrameMatrix"/>
<string key="NSFrameSize">{320, 480}</string>
<reference key="NSSuperview"/>
<object class="NSColor" key="IBUIBackgroundColor">
<int key="NSColorSpace">1</int>
<bytes key="NSRGB">MSAxIDEAA</bytes>
</object>
<bool key="IBUIOpaque">NO</bool>
<bool key="IBUIClearsContextBeforeDrawing">NO</bool>
</object>
</object>
<object class="IBObjectContainer" key="IBDocument.Objects">
<object class="NSMutableArray" key="connectionRecords">
<bool key="EncodedWithXMLCoder">YES</bool>
<object class="IBConnectionRecord">
<object class="IBCocoaTouchOutletConnection" key="connection">
<string key="label">delegate</string>
<reference key="source" ref="841351856"/>
<reference key="destination" ref="987256611"/>
</object>
<int key="connectionID">5</int>
</object>
<object class="IBConnectionRecord">
<object class="IBCocoaTouchOutletConnection" key="connection">
<string key="label">window</string>
<reference key="source" ref="987256611"/>
<reference key="destination" ref="380026005"/>
</object>
<int key="connectionID">6</int>
</object>
<object class="IBConnectionRecord">
<object class="IBCocoaTouchOutletConnection" key="connection">
<string key="label">contentView</string>
<reference key="source" ref="987256611"/>
<reference key="destination" ref="388289409"/>
</object>
<int key="connectionID">8</int>
</object>
<object class="IBConnectionRecord">
<object class="IBCocoaTouchOutletConnection" key="connection">
<string key="label">summaryLabel</string>
<reference key="source" ref="987256611"/>
<reference key="destination" ref="1041619883"/>
</object>
<int key="connectionID">10</int>
</object>
</object>
<object class="IBMutableOrderedSet" key="objectRecords">
<object class="NSArray" key="orderedObjects">
<bool key="EncodedWithXMLCoder">YES</bool>
<object class="IBObjectRecord">
<int key="objectID">0</int>
<reference key="object" ref="0"/>
<reference key="children" ref="1000"/>
<nil key="parent"/>
</object>
<object class="IBObjectRecord">
<int key="objectID">2</int>
<reference key="object" ref="380026005"/>
<object class="NSMutableArray" key="children">
<bool key="EncodedWithXMLCoder">YES</bool>
<reference ref="388289409"/>
</object>
<reference key="parent" ref="0"/>
</object>
<object class="IBObjectRecord">
<int key="objectID">-1</int>
<reference key="object" ref="841351856"/>
<reference key="parent" ref="0"/>
<string key="objectName">File's Owner</string>
</object>
<object class="IBObjectRecord">
<int key="objectID">4</int>
<reference key="object" ref="987256611"/>
<reference key="parent" ref="0"/>
<string key="objectName">ReachabilityAppDelegate</string>
</object>
<object class="IBObjectRecord">
<int key="objectID">7</int>
<reference key="object" ref="388289409"/>
<object class="NSMutableArray" key="children">
<bool key="EncodedWithXMLCoder">YES</bool>
<reference ref="1041619883"/>
</object>
<reference key="parent" ref="380026005"/>
</object>
<object class="IBObjectRecord">
<int key="objectID">9</int>
<reference key="object" ref="1041619883"/>
<reference key="parent" ref="388289409"/>
</object>
<object class="IBObjectRecord">
<int key="objectID">-2</int>
<reference key="object" ref="1071500409"/>
<reference key="parent" ref="0"/>
</object>
</object>
</object>
<object class="NSMutableDictionary" key="flattenedProperties">
<bool key="EncodedWithXMLCoder">YES</bool>
<object class="NSArray" key="dict.sortedKeys">
<bool key="EncodedWithXMLCoder">YES</bool>
<string>-1.CustomClassName</string>
<string>-2.CustomClassName</string>
<string>2.IBAttributePlaceholdersKey</string>
<string>2.IBEditorWindowLastContentRect</string>
<string>2.IBPluginDependency</string>
<string>2.UIWindow.visibleAtLaunch</string>
<string>4.CustomClassName</string>
<string>4.IBPluginDependency</string>
<string>7.IBPluginDependency</string>
<string>9.IBPluginDependency</string>
</object>
<object class="NSMutableArray" key="dict.values">
<bool key="EncodedWithXMLCoder">YES</bool>
<string>UIApplication</string>
<string>UIResponder</string>
<object class="NSMutableDictionary">
<bool key="EncodedWithXMLCoder">YES</bool>
<reference key="dict.sortedKeys" ref="0"/>
<object class="NSMutableArray" key="dict.values">
<bool key="EncodedWithXMLCoder">YES</bool>
</object>
</object>
<string>{{363, 365}, {320, 480}}</string>
<string>com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
<integer value="1"/>
<string>ReachabilityAppDelegate</string>
<string>com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
<string>com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
<string>com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
</object>
</object>
<object class="NSMutableDictionary" key="unlocalizedProperties">
<bool key="EncodedWithXMLCoder">YES</bool>
<reference key="dict.sortedKeys" ref="0"/>
<object class="NSMutableArray" key="dict.values">
<bool key="EncodedWithXMLCoder">YES</bool>
</object>
</object>
<nil key="activeLocalization"/>
<object class="NSMutableDictionary" key="localizations">
<bool key="EncodedWithXMLCoder">YES</bool>
<reference key="dict.sortedKeys" ref="0"/>
<object class="NSMutableArray" key="dict.values">
<bool key="EncodedWithXMLCoder">YES</bool>
</object>
</object>
<nil key="sourceID"/>
<int key="maxID">10</int>
</object>
<object class="IBClassDescriber" key="IBDocument.Classes">
<object class="NSMutableArray" key="referencedPartialClassDescriptions">
<bool key="EncodedWithXMLCoder">YES</bool>
<object class="IBPartialClassDescription">
<string key="className">ReachabilityAppDelegate</string>
<string key="superclassName">NSObject</string>
<object class="NSMutableDictionary" key="outlets">
<bool key="EncodedWithXMLCoder">YES</bool>
<object class="NSArray" key="dict.sortedKeys">
<bool key="EncodedWithXMLCoder">YES</bool>
<string>contentView</string>
<string>summaryLabel</string>
<string>window</string>
</object>
<object class="NSMutableArray" key="dict.values">
<bool key="EncodedWithXMLCoder">YES</bool>
<string>UIView</string>
<string>UILabel</string>
<string>UIWindow</string>
</object>
</object>
<object class="IBClassDescriptionSource" key="sourceIdentifier">
<string key="majorKey">IBProjectSource</string>
<string key="minorKey">Classes/ReachabilityAppDelegate.h</string>
</object>
</object>
</object>
</object>
<int key="IBDocument.localizationMode">0</int>
<object class="NSMutableDictionary" key="IBDocument.PluginDeclaredDependencies">
<string key="NS.key.0">com.apple.InterfaceBuilder.CocoaTouchPlugin.iPhoneOS</string>
<integer value="512" key="NS.object.0"/>
</object>
<object class="NSMutableDictionary" key="IBDocument.PluginDeclaredDevelopmentDependencies">
<string key="NS.key.0">com.apple.InterfaceBuilder.CocoaTouchPlugin.InterfaceBuilder3</string>
<integer value="3000" key="NS.object.0"/>
</object>
<bool key="IBDocument.PluginDeclaredDependenciesTrackSystemTargetVersion">YES</bool>
<string key="IBDocument.LastKnownRelativeProjectPath">Reachability.xcodeproj</string>
<int key="IBDocument.defaultPropertyAccessControl">3</int>
<string key="IBCocoaTouchPluginVersion">3.1</string>
</data>
</archive>

60
ReachabilitySample/MainWindow.xib.designer.cs сгенерированный
Просмотреть файл

@ -1,60 +0,0 @@
// ------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a tool.
// Mono Runtime Version: 4.0.30319.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </autogenerated>
// ------------------------------------------------------------------------------
namespace reachability {
// Base type probably should be MonoTouch.Foundation.NSObject or subclass
[Foundation.Register("ReachabilityAppDelegate")]
public partial class ReachabilityAppDelegate {
private UIKit.UIWindow __mt_window;
private UIKit.UIView __mt_contentView;
private UIKit.UILabel __mt_summaryLabel;
#pragma warning disable 0169
[Foundation.Connect("window")]
private UIKit.UIWindow window {
get {
this.__mt_window = ((UIKit.UIWindow)(this.GetNativeField("window")));
return this.__mt_window;
}
set {
this.__mt_window = value;
this.SetNativeField("window", value);
}
}
[Foundation.Connect("contentView")]
private UIKit.UIView contentView {
get {
this.__mt_contentView = ((UIKit.UIView)(this.GetNativeField("contentView")));
return this.__mt_contentView;
}
set {
this.__mt_contentView = value;
this.SetNativeField("contentView", value);
}
}
[Foundation.Connect("summaryLabel")]
private UIKit.UILabel summaryLabel {
get {
this.__mt_summaryLabel = ((UIKit.UILabel)(this.GetNativeField("summaryLabel")));
return this.__mt_summaryLabel;
}
set {
this.__mt_summaryLabel = value;
this.SetNativeField("summaryLabel", value);
}
}
}
}

Просмотреть файл

@ -0,0 +1,143 @@
using System;
using System.Net;
using SystemConfiguration;
using CoreFoundation;
namespace Reachability {
public enum NetworkStatus {
NotReachable,
ReachableViaCarrierDataNetwork,
ReachableViaWiFiNetwork
}
public static class Reachability
{
public static string HostName = "www.google.com";
public static bool IsReachableWithoutRequiringConnection (NetworkReachabilityFlags flags)
{
// Is it reachable with the current network configuration?
bool isReachable = (flags & NetworkReachabilityFlags.Reachable) != 0;
// Do we need a connection to reach it?
bool noConnectionRequired = (flags & NetworkReachabilityFlags.ConnectionRequired) == 0
|| (flags & NetworkReachabilityFlags.IsWWAN) != 0;
return isReachable && noConnectionRequired;
}
// Is the host reachable with the current network configuration
public static bool IsHostReachable(string host)
{
if (string.IsNullOrEmpty(host))
return false;
using (var r = new NetworkReachability(host)) {
NetworkReachabilityFlags flags;
if (r.TryGetFlags(out flags))
return IsReachableWithoutRequiringConnection(flags);
}
return false;
}
//
// Raised every time there is an interesting reachable event,
// we do not even pass the info as to what changed, and
// we lump all three status we probe into one
//
public static event EventHandler ReachabilityChanged;
static void OnChange(NetworkReachabilityFlags flags)
{
var h = ReachabilityChanged;
if (h != null)
h(null, EventArgs.Empty);
}
//
// Returns true if it is possible to reach the AdHoc WiFi network
// and optionally provides extra network reachability flags as the
// out parameter
//
static NetworkReachability adHocWiFiNetworkReachability;
public static bool IsAdHocWiFiNetworkAvailable (out NetworkReachabilityFlags flags)
{
if (adHocWiFiNetworkReachability == null) {
adHocWiFiNetworkReachability = new NetworkReachability(new IPAddress(new byte [] { 169, 254, 0, 0 }));
adHocWiFiNetworkReachability.SetNotification(OnChange);
adHocWiFiNetworkReachability.Schedule(CFRunLoop.Current, CFRunLoop.ModeDefault);
}
return adHocWiFiNetworkReachability.TryGetFlags(out flags) && IsReachableWithoutRequiringConnection(flags);
}
static NetworkReachability defaultRouteReachability;
static bool IsNetworkAvailable(out NetworkReachabilityFlags flags)
{
if (defaultRouteReachability == null) {
defaultRouteReachability = new NetworkReachability(new IPAddress(0));
defaultRouteReachability.SetNotification(OnChange);
defaultRouteReachability.Schedule(CFRunLoop.Current, CFRunLoop.ModeDefault);
}
return defaultRouteReachability.TryGetFlags(out flags) && IsReachableWithoutRequiringConnection(flags);
}
static NetworkReachability remoteHostReachability;
public static NetworkStatus RemoteHostStatus()
{
NetworkReachabilityFlags flags;
bool reachable;
if (remoteHostReachability == null) {
remoteHostReachability = new NetworkReachability (HostName);
// Need to probe before we queue, or we wont get any meaningful values
// this only happens when you create NetworkReachability from a hostname
reachable = remoteHostReachability.TryGetFlags (out flags);
remoteHostReachability.SetNotification (OnChange);
remoteHostReachability.Schedule (CFRunLoop.Current, CFRunLoop.ModeDefault);
} else {
reachable = remoteHostReachability.TryGetFlags (out flags);
}
if (!reachable)
return NetworkStatus.NotReachable;
if (!IsReachableWithoutRequiringConnection(flags))
return NetworkStatus.NotReachable;
return (flags & NetworkReachabilityFlags.IsWWAN) != 0 ?
NetworkStatus.ReachableViaCarrierDataNetwork : NetworkStatus.ReachableViaWiFiNetwork;
}
public static NetworkStatus InternetConnectionStatus ()
{
NetworkReachabilityFlags flags;
bool defaultNetworkAvailable = IsNetworkAvailable(out flags);
if (defaultNetworkAvailable && ((flags & NetworkReachabilityFlags.IsDirect) != 0))
return NetworkStatus.NotReachable;
else if ((flags & NetworkReachabilityFlags.IsWWAN) != 0)
return NetworkStatus.ReachableViaCarrierDataNetwork;
else if (flags == 0)
return NetworkStatus.NotReachable;
return NetworkStatus.ReachableViaWiFiNetwork;
}
public static NetworkStatus LocalWifiConnectionStatus()
{
NetworkReachabilityFlags flags;
if (IsAdHocWiFiNetworkAvailable(out flags))
if ((flags & NetworkReachabilityFlags.IsDirect) != 0)
return NetworkStatus.ReachableViaWiFiNetwork;
return NetworkStatus.NotReachable;
}
}
}

Просмотреть файл

@ -1,156 +1,143 @@
using System; using System;
using System.Net; using System.Net;
using SystemConfiguration; using SystemConfiguration;
using CoreFoundation; using CoreFoundation;
public enum NetworkStatus namespace Reachability {
{ public enum NetworkStatus {
NotReachable, NotReachable,
ReachableViaCarrierDataNetwork, ReachableViaCarrierDataNetwork,
ReachableViaWiFiNetwork ReachableViaWiFiNetwork
} }
public static class Reachability public static class Reachability
{ {
public static string HostName = "www.google.com"; public static string HostName = "www.google.com";
public static bool IsReachableWithoutRequiringConnection(NetworkReachabilityFlags flags) public static bool IsReachableWithoutRequiringConnection (NetworkReachabilityFlags flags)
{ {
// Is it reachable with the current network configuration? // Is it reachable with the current network configuration?
bool isReachable = (flags & NetworkReachabilityFlags.Reachable) != 0; bool isReachable = (flags & NetworkReachabilityFlags.Reachable) != 0;
// Do we need a connection to reach it? // Do we need a connection to reach it?
bool noConnectionRequired = (flags & NetworkReachabilityFlags.ConnectionRequired) == 0; bool noConnectionRequired = (flags & NetworkReachabilityFlags.ConnectionRequired) == 0
|| (flags & NetworkReachabilityFlags.IsWWAN) != 0;
// Since the network stack will automatically try to get the WAN up,
// probe that return isReachable && noConnectionRequired;
if ((flags & NetworkReachabilityFlags.IsWWAN) != 0) }
noConnectionRequired = true;
// Is the host reachable with the current network configuration
return isReachable && noConnectionRequired; public static bool IsHostReachable(string host)
} {
if (string.IsNullOrEmpty(host))
// Is the host reachable with the current network configuration return false;
public static bool IsHostReachable(string host)
{ using (var r = new NetworkReachability(host)) {
if (string.IsNullOrEmpty(host)) NetworkReachabilityFlags flags;
return false;
if (r.TryGetFlags(out flags))
using (var r = new NetworkReachability(host)) return IsReachableWithoutRequiringConnection(flags);
{ }
NetworkReachabilityFlags flags; return false;
}
if (r.TryGetFlags(out flags))
{ //
return IsReachableWithoutRequiringConnection(flags); // Raised every time there is an interesting reachable event,
} // we do not even pass the info as to what changed, and
} // we lump all three status we probe into one
return false; //
} public static event EventHandler ReachabilityChanged;
// static void OnChange(NetworkReachabilityFlags flags)
// Raised every time there is an interesting reachable event, {
// we do not even pass the info as to what changed, and var h = ReachabilityChanged;
// we lump all three status we probe into one if (h != null)
// h(null, EventArgs.Empty);
public static event EventHandler ReachabilityChanged; }
static void OnChange(NetworkReachabilityFlags flags) //
{ // Returns true if it is possible to reach the AdHoc WiFi network
var h = ReachabilityChanged; // and optionally provides extra network reachability flags as the
if (h != null) // out parameter
h(null, EventArgs.Empty); //
} static NetworkReachability adHocWiFiNetworkReachability;
// public static bool IsAdHocWiFiNetworkAvailable (out NetworkReachabilityFlags flags)
// Returns true if it is possible to reach the AdHoc WiFi network {
// and optionally provides extra network reachability flags as the if (adHocWiFiNetworkReachability == null) {
// out parameter adHocWiFiNetworkReachability = new NetworkReachability(new IPAddress(new byte [] { 169, 254, 0, 0 }));
// adHocWiFiNetworkReachability.SetNotification(OnChange);
static NetworkReachability adHocWiFiNetworkReachability; adHocWiFiNetworkReachability.Schedule(CFRunLoop.Current, CFRunLoop.ModeDefault);
}
public static bool IsAdHocWiFiNetworkAvailable(out NetworkReachabilityFlags flags)
{ return adHocWiFiNetworkReachability.TryGetFlags(out flags) && IsReachableWithoutRequiringConnection(flags);
if (adHocWiFiNetworkReachability == null) }
{
adHocWiFiNetworkReachability = new NetworkReachability(new IPAddress(new byte [] { 169, 254, 0, 0 })); static NetworkReachability defaultRouteReachability;
adHocWiFiNetworkReachability.SetNotification(OnChange);
adHocWiFiNetworkReachability.Schedule(CFRunLoop.Current, CFRunLoop.ModeDefault); static bool IsNetworkAvailable(out NetworkReachabilityFlags flags)
} {
if (defaultRouteReachability == null) {
return adHocWiFiNetworkReachability.TryGetFlags(out flags) && IsReachableWithoutRequiringConnection(flags); defaultRouteReachability = new NetworkReachability(new IPAddress(0));
} defaultRouteReachability.SetNotification(OnChange);
defaultRouteReachability.Schedule(CFRunLoop.Current, CFRunLoop.ModeDefault);
static NetworkReachability defaultRouteReachability; }
return defaultRouteReachability.TryGetFlags(out flags) && IsReachableWithoutRequiringConnection(flags);
static bool IsNetworkAvailable(out NetworkReachabilityFlags flags) }
{
if (defaultRouteReachability == null) static NetworkReachability remoteHostReachability;
{
defaultRouteReachability = new NetworkReachability(new IPAddress(0)); public static NetworkStatus RemoteHostStatus()
defaultRouteReachability.SetNotification(OnChange); {
defaultRouteReachability.Schedule(CFRunLoop.Current, CFRunLoop.ModeDefault); NetworkReachabilityFlags flags;
} bool reachable;
return defaultRouteReachability.TryGetFlags(out flags) && IsReachableWithoutRequiringConnection(flags);
} if (remoteHostReachability == null) {
remoteHostReachability = new NetworkReachability (HostName);
static NetworkReachability remoteHostReachability;
// Need to probe before we queue, or we wont get any meaningful values
public static NetworkStatus RemoteHostStatus() // this only happens when you create NetworkReachability from a hostname
{ reachable = remoteHostReachability.TryGetFlags (out flags);
NetworkReachabilityFlags flags;
bool reachable; remoteHostReachability.SetNotification (OnChange);
remoteHostReachability.Schedule (CFRunLoop.Current, CFRunLoop.ModeDefault);
if (remoteHostReachability == null) } else {
{ reachable = remoteHostReachability.TryGetFlags (out flags);
remoteHostReachability = new NetworkReachability(HostName); }
// Need to probe before we queue, or we wont get any meaningful values if (!reachable)
// this only happens when you create NetworkReachability from a hostname return NetworkStatus.NotReachable;
reachable = remoteHostReachability.TryGetFlags(out flags);
if (!IsReachableWithoutRequiringConnection(flags))
remoteHostReachability.SetNotification(OnChange); return NetworkStatus.NotReachable;
remoteHostReachability.Schedule(CFRunLoop.Current, CFRunLoop.ModeDefault);
} return (flags & NetworkReachabilityFlags.IsWWAN) != 0 ?
else NetworkStatus.ReachableViaCarrierDataNetwork : NetworkStatus.ReachableViaWiFiNetwork;
reachable = remoteHostReachability.TryGetFlags(out flags); }
if (!reachable) public static NetworkStatus InternetConnectionStatus ()
return NetworkStatus.NotReachable; {
NetworkReachabilityFlags flags;
if (!IsReachableWithoutRequiringConnection(flags)) bool defaultNetworkAvailable = IsNetworkAvailable(out flags);
return NetworkStatus.NotReachable; if (defaultNetworkAvailable && ((flags & NetworkReachabilityFlags.IsDirect) != 0))
return NetworkStatus.NotReachable;
if ((flags & NetworkReachabilityFlags.IsWWAN) != 0) else if ((flags & NetworkReachabilityFlags.IsWWAN) != 0)
return NetworkStatus.ReachableViaCarrierDataNetwork; return NetworkStatus.ReachableViaCarrierDataNetwork;
else if (flags == 0)
return NetworkStatus.ReachableViaWiFiNetwork; return NetworkStatus.NotReachable;
} return NetworkStatus.ReachableViaWiFiNetwork;
}
public static NetworkStatus InternetConnectionStatus()
{ public static NetworkStatus LocalWifiConnectionStatus()
NetworkReachabilityFlags flags; {
bool defaultNetworkAvailable = IsNetworkAvailable(out flags); NetworkReachabilityFlags flags;
if (defaultNetworkAvailable && ((flags & NetworkReachabilityFlags.IsDirect) != 0)) if (IsAdHocWiFiNetworkAvailable(out flags))
{ if ((flags & NetworkReachabilityFlags.IsDirect) != 0)
return NetworkStatus.NotReachable; return NetworkStatus.ReachableViaWiFiNetwork;
}
else if ((flags & NetworkReachabilityFlags.IsWWAN) != 0) return NetworkStatus.NotReachable;
return NetworkStatus.ReachableViaCarrierDataNetwork; }
else if (flags == 0) }
return NetworkStatus.NotReachable;
return NetworkStatus.ReachableViaWiFiNetwork;
}
public static NetworkStatus LocalWifiConnectionStatus()
{
NetworkReachabilityFlags flags;
if (IsAdHocWiFiNetworkAvailable(out flags))
{
if ((flags & NetworkReachabilityFlags.IsDirect) != 0)
return NetworkStatus.ReachableViaWiFiNetwork;
}
return NetworkStatus.NotReachable;
}
} }

Просмотреть файл

@ -3,59 +3,60 @@
<PropertyGroup> <PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">iPhoneSimulator</Platform> <Platform Condition=" '$(Platform)' == '' ">iPhoneSimulator</Platform>
<ProjectTypeGuids>{FEACFBD2-3405-455C-9665-78FE426C6842};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<ProductVersion>8.0.30703</ProductVersion> <ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion> <SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{E1356D0A-1572-4157-BD97-05F0B9DA832E}</ProjectGuid> <ProjectGuid>{E1356D0A-1572-4157-BD97-05F0B9DA832E}</ProjectGuid>
<ProjectTypeGuids>{FEACFBD2-3405-455C-9665-78FE426C6842};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<OutputType>Exe</OutputType> <OutputType>Exe</OutputType>
<RootNamespace>reachability</RootNamespace> <RootNamespace>reachability</RootNamespace>
<AssemblyName>reachability</AssemblyName> <AssemblyName>reachability</AssemblyName>
<TargetFrameworkIdentifier>Xamarin.iOS</TargetFrameworkIdentifier>
<TargetFrameworkVersion>v1.0</TargetFrameworkVersion> <TargetFrameworkVersion>v1.0</TargetFrameworkVersion>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|iPhoneSimulator' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|iPhoneSimulator' ">
<DebugSymbols>True</DebugSymbols> <DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType> <DebugType>full</DebugType>
<Optimize>False</Optimize> <Optimize>false</Optimize>
<OutputPath>bin\iPhoneSimulator\Debug</OutputPath> <OutputPath>bin\iPhoneSimulator\Debug</OutputPath>
<DefineConstants>DEBUG</DefineConstants> <DefineConstants>DEBUG</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
<MtouchLink>None</MtouchLink>
<MtouchDebug>True</MtouchDebug>
<MtouchArch>i386</MtouchArch> <MtouchArch>i386</MtouchArch>
<MtouchI18n> <MtouchI18n>
</MtouchI18n> </MtouchI18n>
<MtouchDebug>true</MtouchDebug>
<MtouchLink>None</MtouchLink>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|iPhoneSimulator' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|iPhoneSimulator' ">
<DebugType>none</DebugType> <DebugType>none</DebugType>
<Optimize>False</Optimize> <Optimize>false</Optimize>
<OutputPath>bin\iPhoneSimulator\Release</OutputPath> <OutputPath>bin\iPhoneSimulator\Release</OutputPath>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
<MtouchLink>None</MtouchLink>
<MtouchArch>i386</MtouchArch> <MtouchArch>i386</MtouchArch>
<MtouchLink>None</MtouchLink>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|iPhone' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|iPhone' ">
<DebugSymbols>True</DebugSymbols> <DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType> <DebugType>full</DebugType>
<Optimize>False</Optimize> <Optimize>false</Optimize>
<OutputPath>bin\iPhone\Debug</OutputPath> <OutputPath>bin\iPhone\Debug</OutputPath>
<DefineConstants>DEBUG</DefineConstants> <DefineConstants>DEBUG</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
<CodesignKey>iPhone Developer</CodesignKey>
<MtouchDebug>True</MtouchDebug>
<MtouchArch>ARMv7</MtouchArch> <MtouchArch>ARMv7</MtouchArch>
<IpaPackageName>
</IpaPackageName>
<CodesignKey>iPhone Developer</CodesignKey>
<MtouchDebug>true</MtouchDebug>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|iPhone' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|iPhone' ">
<DebugType>none</DebugType> <DebugType>none</DebugType>
<Optimize>False</Optimize> <Optimize>false</Optimize>
<OutputPath>bin\iPhone\Release</OutputPath> <OutputPath>bin\iPhone\Release</OutputPath>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
<CodesignKey>iPhone Developer</CodesignKey>
<MtouchArch>ARMv7, ARM64</MtouchArch> <MtouchArch>ARMv7, ARM64</MtouchArch>
<CodesignKey>iPhone Developer</CodesignKey>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="System" /> <Reference Include="System" />
@ -64,14 +65,16 @@
<Reference Include="Xamarin.iOS" /> <Reference Include="Xamarin.iOS" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="MainWindow.xib.designer.cs">
<DependentUpon>MainWindow.xib</DependentUpon>
</Compile>
<Compile Include="reachability.cs" />
<Compile Include="AppDelegate.cs" /> <Compile Include="AppDelegate.cs" />
<Compile Include="MainViewController.cs" />
<Compile Include="MainViewController.designer.cs">
<DependentUpon>MainViewController.cs</DependentUpon>
</Compile>
<Compile Include="Main.cs" />
<Compile Include="Reachability.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<InterfaceDefinition Include="MainWindow.xib" /> <InterfaceDefinition Include="Main.storyboard" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Content Include="Network.png" /> <Content Include="Network.png" />

Просмотреть файл

@ -1,7 +1,7 @@
 
Microsoft Visual Studio Solution File, Format Version 11.00 Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010 # Visual Studio 2010
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "reachability", "reachability.csproj", "{E1356D0A-1572-4157-BD97-05F0B9DA832E}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Reachability", "Reachability.csproj", "{E1356D0A-1572-4157-BD97-05F0B9DA832E}"
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -20,7 +20,4 @@ Global
{E1356D0A-1572-4157-BD97-05F0B9DA832E}.Release|iPhoneSimulator.ActiveCfg = Release|iPhoneSimulator {E1356D0A-1572-4157-BD97-05F0B9DA832E}.Release|iPhoneSimulator.ActiveCfg = Release|iPhoneSimulator
{E1356D0A-1572-4157-BD97-05F0B9DA832E}.Release|iPhoneSimulator.Build.0 = Release|iPhoneSimulator {E1356D0A-1572-4157-BD97-05F0B9DA832E}.Release|iPhoneSimulator.Build.0 = Release|iPhoneSimulator
EndGlobalSection EndGlobalSection
GlobalSection(MonoDevelopProperties) = preSolution
StartupItem = reachability.csproj
EndGlobalSection
EndGlobal EndGlobal