Skip to content

Commit

Permalink
Merge pull request #1 from FromAtom/feature/support-simulator-with-wi…
Browse files Browse the repository at this point in the history
…red-network

有線LAN接続したMac上のシミュレーターで常にnetworkErrorになってしまう問題を解決
  • Loading branch information
kvvzr authored Aug 6, 2024
2 parents 698ef23 + 8f5bcae commit eeefb05
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 7 deletions.
23 changes: 22 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,25 @@ do {
```

## Installation
Swift Package Managerを使ってインストールすることができます。Xcodeの `File > Add Packages...` から `https://github.com/pixiv/ios-tutorial-api-mock` を入力して利用できます
Swift Package Managerを使ってインストールすることができます。Xcodeの `File > Add Packages...` から `https://github.com/pixiv/ios-tutorial-api-mock` を入力して利用できます

## Tips
有線LANを接続したMac上のiOS Simulatorで開発をしている場合、 `IllustError.networkError` が発生してAPIリクエストに失敗します。
次のコードに書き換えることで、シミュレーター上で動かすことが可能になります。

```swift
import IllustAPIMock

let api = IllustAPIMock()
api.networkMonitor = NetworkMonitorImpl(interfaceType: .wiredEthernet) // この行を追加

do {
let rankingIllusts = try await api.getRanking()
let recommendedIllusts = try await api.getRecommended()
_ = try await api.postIsFavorited(illustID: ..., isFavorited: true)
} catch {
...
}
```

ただし、この変更を行ったコードを実機で動かした場合は、iPhone/iPadが有線LANに接続していない場合に `IllustError.networkError` が発生する点に注意して下さい。
8 changes: 5 additions & 3 deletions Sources/IllustAPIMock/IllustAPIMock.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@ import CoreData
import Foundation

public class IllustAPIMock {
var networkMonitor: NetworkMonitor = NetworkMonitorImpl()
public var networkMonitor: NetworkMonitor = NetworkMonitorImpl() {
didSet {
networkMonitor.start()
}
}

private static let databaseName = "Illusts"
private static let entityName = "IllustEntity"
Expand All @@ -16,8 +20,6 @@ public class IllustAPIMock {
container.loadPersistentStores { _, _ in }

setup()

networkMonitor.start()
}

public func getRanking(offset: Int = 0) async throws -> [Illust] {
Expand Down
13 changes: 10 additions & 3 deletions Sources/IllustAPIMock/NetworkMonitor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,18 @@ public protocol NetworkMonitor {
}

public class NetworkMonitorImpl: NetworkMonitor {
private let monitor = NWPathMonitor(requiredInterfaceType: .wifi)
private let queue = DispatchQueue.global(qos: .background)
private let monitor: NWPathMonitor

public init(interfaceType: NWInterface.InterfaceType = .wifi) {
monitor = NWPathMonitor(requiredInterfaceType: interfaceType)
}

deinit {
monitor.cancel()
}

public func start() {
monitor.start(queue: queue)
monitor.start(queue: .global(qos: .background))
}

public func isConnected() -> Bool {
Expand Down

0 comments on commit eeefb05

Please sign in to comment.