2014-10-10 00:00

[Swift-d19] - Basic - 橋接第三方 Objc library - Reachability and Bridge.h

本日專案的 Github link

由於 Swift 剛推出不到一年

有許多的 third-party library 一定還沒轉換成 Swift

或者是作者沒心力轉會成 Swift

但是有些套件非常方便,那在 Swift 要怎麼使用 Objective-C 的套件呢?

Xcode 有提供橋接的方式,非常好用

接下來就介紹一下如何使用吧!

以下的例子是一個叫做 Reachability 的套件

它可以簡單地幫我們判斷是否有網路連線 3g or wifi 之類的

所以我們先下載這個套件吧!

https://github.com/tonymillion/Reachability

下載解壓縮後

將 .h 和 .m 檔拖曳進 Xcode 專案中

image

接下來 Xcode 就會問一個非常重要的問題!:

image

是否要建立橋接的 .h 檔案!

當然是選擇建立囉~

此時的專案結構就會變成這樣:

image

再來編輯 bridge-header.h 檔

將想要橋接的 objc 套件 import 進去

#import "Reachability.h"

這樣我們就可以在 Swift 中直接使用該套件的類別與方法了!

接下來就讓我們試試看!

在 ViewController 中加入以下程式碼:

//
//  ViewController.swift
//  BridgeObjcDemo
//
//  Created by Jerry Huang on 2014/10/18.
//  Copyright (c) 2014年 kerkerj. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        
        var isConnected = checkNetworkConnection()
        
        let alert = UIAlertView()
        alert.title = "Network Connection"
        
        if isConnected {
            alert.message = "You're online!"
        } else {
            alert.message = "You're offline!"
        }
        
        alert.addButtonWithTitle("OK")
        alert.show()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func checkNetworkConnection() -> Bool {
        let reachability: Reachability = Reachability.reachabilityForInternetConnection()
        let networkStatus: NetworkStatus = reachability.currentReachabilityStatus()
        
        println(networkStatus.toRaw())
        
        switch (networkStatus.toRaw()) {
        case 0:
            println("[Network Status]: NotReachable")
        case 1:
            println("[Network Status]: ReachableViaWWAN")
        case 2:
            println("[Network Status]: ReachableViaWiFi")
        default:
            break
        }
        
        return networkStatus.toRaw() != 0
    }
}

簡單的說,我們寫了一個方法,使用 Reachability 偵測網路連線

在 ViewDidLoad 時,偵測是否有網路連線

跳一個 Alert 會告訴你是有連線還是沒有連線

image

不過在這邊,我不曉得如何讓模擬器關掉連線,

所以沒辦法提供 offline 的圖

但是我實際安裝到手機後,將 wifi 功能關掉後的確是有跳出 offline 的

哈哈 雖然說沒圖沒真相但是…XD

橋接第三方套件就是那麼簡單! :D

Share

comments powered by Disqus