英文:
Swift Combine and iOS version limitations?
问题
以下是翻译好的部分:
例如,AppTrackingTransparency 在 iOS 14+ 中存在,但一个应用支持 iOS 13+。
我使用了以下代码:
@available(iOS 14, *)
func requestATTPermissions() -> Future<ATTrackingManager.AuthorizationStatus, Never> {
...
}
if #available(iOS 14, *) {
requestATTPermissions()
.sink { [weak self] _ in
self?.completion?()
}
.store(in: &combineSubscriptionCollector.subscriptions)
} else {
completion?()
}
但是否可以将 if #available(iOS 14, *) {
移动到 Future
/AnyPublisher
中,在 iOS 13 中工作方式类似于 Just(())
,而在 iOS14+ 中请求 ATT?类似于以下方式:
Just(()).map {
if #available(iOS 14, *) {
return requestATTPermissions()
.map { status in ... }
} else {
return Just(())
}
}
.sink { [weak self] _ in
self?.completion?()
}
.store(in: &combineSubscriptionCollector.subscriptions)
英文:
For example AppTrackingTransparency exists in iOS 14+ but an app supports iOS 13+.
I used the following code:
@available(iOS 14, *)
func requestATTPermissions() ->
Future<ATTrackingManager.AuthorizationStatus, Never> {
...
}
if #available(iOS 14, *) {
requestATTPermissions()
.sink { [weak self] _ in
self?.completion?()
}
.store(in: &combineSubscriptionCollector.subscriptions)
} else {
completion?()
}
But is it possible to move if #available(iOS 14, *) {
into Future
/AnyPublisher
which in iOS 13 works like Just(())
and in iOS14+ requests ATT? Somehow like this:
Just(()).map {
if #available(iOS 14, *) {
return requestATTPermissions()
.map { status in ... }
} else {
return Just(())
}
}
.sink { [weak self] _ in
self?.completion?()
}
.store(in: &combineSubscriptionCollector.subscriptions)
答案1
得分: 1
If I understand correctly, you just need to use flatMap
instead of map
:
Just(()).flatMap { _ in
if #available(iOS 14, *) {
return requestATTPermisions().map { status in
// 这里不需要返回任何内容...
}.eraseToAnyPublisher()
} else {
return Just(()).eraseToAnyPublisher()
}
}
// .sink and .store...
Though I think this is easier to read and understand:
let publisher: AnyPublisher<(), Never>
if #available(iOS 14, *) {
publisher = requestATTPermisions().map { status in
// ...
}.eraseToAnyPublisher()
} else {
publisher = Just(()).eraseToAnyPublisher()
}
publisher.sink { ... }.store(in: ...)
英文:
If I understand correctly, you just need to use flatMap
instead of map
:
Just(()).flatMap { _ in
if #available(iOS 14, *) {
return requestATTPermisions().map { status in
// do not return anything here...
}.eraseToAnyPublisher()
} else {
return Just(()).eraseToAnyPublisher()
}
}
// .sink and .store...
Though I think this is easier to read and understand:
let publisher: AnyPublisher<(), Never>
if #available(iOS 14, *) {
publisher = requestATTPermisions().map { status in
// ...
}.eraseToAnyPublisher()
} else {
publisher = Just(()).eraseToAnyPublisher()
}
publisher.sink { ... }.store(in: ...)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论