ios 網速監控 iOS開發網路篇 監測網路狀態

2021-10-19 15:59:40 字數 3004 閱讀 6191

一、說明

在網路應用中,需要對使用者裝置的網路狀態進行實時監控,有兩個目的:

(1)讓使用者了解自己的網路狀態,防止一些誤會(比如怪應用無能)

(2)根據使用者的網路狀態進行智慧型處理,節省使用者流量,提高使用者體驗

沒有網路:只顯示離線的快取資料

reachability 類中定義了三種網路狀態:

>typedef numnetworkstatus;

蘋果官方提供了乙個叫reachability的示例程式,便於開發者檢測網路狀態

二、監測網路狀態

reachability的使用步驟

新增框架systemconfiguration.framework

新增源**

示例://比如檢測某一特定站點的接續狀況,可以使用下面的**

4.檢查當前網路環境

//程式啟動時,如果想檢測可用的網路環境,可以像這樣來使用

//是否wifi

+ (bool)isenablewifi

return ([[reachability reachabiliyforlocalwifi] currentreachabilitystatus] != notreachable);

//是否3g

+ (bool)isenable3g

return ([[reachability reachabiliyforinternetconnetion] currentreachabilitystatus] != notreachable);

連線狀態實時通知

網路連線狀態的實時檢查,通知在網路應用中也是十分必要的。接續狀態發生變化時,需要及時地通知使用者。由於reachability1.5版與2.0版有一些變化,這裡分開來說明使用方法。

reachability 1.5

#import "reachability.h"

networkstatus remotehoststatus;

@property networkstatus remotehoststatus;

@end

@synthesize remotehoststatus;

// 更新網路狀態

- (void)updatestatus {

self.remotehoststatus = [[reachability sharedreachability] remotehoststatus];

// 通知網路狀態

- (void)reachabilitychanged:(nsnotification *)note {

[self updatestatus];

if (self.remotehoststatus == notreachable) {

delegate:nil cancelbuttontitle:@"ok" otherbuttontitles: nil];

[alert show];

[alert release];

// 程式啟動器,啟動網路監視

// 設定網路檢測的站點

[[reachability sharedreachability] setnetworkstatusnotificationsenabled:yes];

// 設定網路狀態變化時的通知函式

[[nsnotificationcenter defaultcenter] addobserver:self selector:@selector(reachabilitychanged:)

name:@"knetworkreachabilitychangednotification" object:nil];

[self updatestatus];

- (void)dealloc {

// 刪除通知物件

[[nsnotificationcenter defaultcenter] removeobserver:self];

reachability 2.0

@class reachability;

reachability  *hostreach;

@end

- (void)reachabilitychanged:(nsnotification *)note {

reachability* curreach = [note object];

nsparameterassert([curreach iskindofclass: [reachability class]]);

networkstatus status = [curreach currentreachabilitystatus];

if (status == notreachable) {

message:@"notreachable"

delegate:nil

cancelbuttontitle:@"yes" otherbuttontitles:nil];

[alert show];

// 監測網路情況

[[nsnotificationcenter defaultcenter] addobserver:self

selector:@selector(reachabilitychanged:)

name: kreachabilitychangednotification

object: nil];

hostreach = [[reachability reachabilitywithhostname:@"www.google.com"] retain];

[hostreach startnotifer];

iOS開發網路篇 NSURLConnection

s簡介 如果你使用的是 請求的話,那麼你需要知道四個方法 1 當接受到伺服器響應的時候會呼叫 response 響應頭 void connection nsurlconnection connection didreceiveresponse nsurlresponse response 2 當接受...

iOS開發網路篇 JSON介紹

2.傳送請求給伺服器 帶上賬號和密碼 新增乙個遮罩,禁止使用者操作 mbprogresshud showmessage 正在努力載入中.1.設定請求路徑 nsstring urlstr nsstring stringwithformat self.username.text,self.pwd.tex...

iOS開發網路篇 HTTP協議

ios開發網路篇 http協議 說明 apache tomcat伺服器必須占用8080埠 一 url 1.基本介紹 url的全稱是uniform resource locator 統一資源定位符 通過1個url,能找到網際網路上唯一的1個資源 url就是資源的位址 位置,網際網路上的每個資源都有乙個...