下面是我的想法,当用户通过$artistName
进行搜索时,我想展示这些数据,然后组合框架可以帮助我从服务器请求数据。
我不知道我错了哪一步。当我试图通过模拟器获取数据时。它将显示未知的错误和其余的这些。
2020-10-23 03:56:38.220523+0800 PodcastSearchV2[42967:667554] [] nw_protocol_get_quic_image_block_invoke dlopen libquic failed
Fetch failed: Unknown error
2020-10-23 03:56:40.114906+0800 PodcastSearchV2[42967:667546] [connection] nw_connection_copy_protocol_metadata [C2] Client called nw_connection_copy_protocol_metadata on unconnected nw_connection
2020-10-23 03:56:40.115071+0800 PodcastSearchV2[42967:667546] [connection] nw_connection_copy_protocol_metadata [C2] Client called nw_connection_copy_protocol_metadata on unconnected nw_connection
2020-10-23 03:56:40.115255+0800 PodcastSearchV2[42967:667546] [connection] nw_connection_copy_protocol_metadata [C2] Client called nw_connection_copy_protocol_metadata on unconnected nw_connection
2020-10-23 03:56:40.115360+0800 PodcastSearchV2[42967:667546] [connection] nw_connection_copy_protocol_metadata [C2] Client called nw_connection_copy_protocol_metadata on unconnected nw_connection
2020-10-23 03:56:40.115516+0800 PodcastSearchV2[42967:667546] [connection] nw_connection_copy_connected_local_endpoint [C2] Client called nw_connection_copy_connected_local_endpoint on unconnected nw_connection
2020-10-23 03:56:40.115613+0800 PodcastSearchV2[42967:667546] [connection] nw_connection_copy_connected_remote_endpoint [C2] Client called nw_connection_copy_connected_remote_endpoint on unconnected nw_connection
2020-10-23 03:56:40.115723+0800 PodcastSearchV2[42967:667546] [connection] nw_connection_copy_connected_path [C2] Client called nw_connection_copy_connected_path on unconnected nw_connection
2020-10-23 03:56:40.115924+0800 PodcastSearchV2[42967:667546] Connection 2: unable to determine interface type without an established connection
2020-10-23 03:56:40.116069+0800 PodcastSearchV2[42967:667546] Connection 2: unable to determine interface classification without an established connection
2020-10-23 03:56:40.116381+0800 PodcastSearchV2[42967:667546] [connection] nw_connection_copy_protocol_metadata [C2] Client called nw_connection_copy_protocol_metadata on unconnected nw_connection
2020-10-23 03:56:40.120441+0800 PodcastSearchV2[42967:667546] [connection] nw_connection_copy_metadata [C2] Client called nw_connection_copy_metadata on unconnected nw_connection
2020-10-23 03:56:40.120579+0800 PodcastSearchV2[42967:667546] Connection 2: unable to determine interface type without an established connection
2020-10-23 03:56:40.121823+0800 PodcastSearchV2[42967:667546] Connection 2: unable to determine interface type without an established connection
这是我的回应。
struct DataResponseSpotify: Codable {
var episodes: PodcastItemSpotify
}
struct PodcastItemSpotify: Codable {
var items: [PodcastItemsDetailsSpotify]
}
struct PodcastItemsDetailsSpotify: Codable, Identifiable {
let id: String
let description: String
let images: [Images]
let name: String
let external: String
var externalURL: URL? {
return URL(string: external)
}
enum CodingKeys: String, CodingKey {
case id
case description
case images
case name
case external = "external_urls"
}
}
struct Images: Codable {
let url: String
var imageURL: URL? {
return URL(string: url)
}
enum CodingKeys: String, CodingKey {
case url
}
}
struct Token: Codable {
let accessToken: String
enum CodingKeys: String, CodingKey {
case accessToken = "access_token"
}
}
我就是这样在模型里写的。
class DataObserverSpotify: ObservableObject {
@Published var artistName = ""
@Published var token = ""
@Published var fetchResult = [PodcastItemsDetailsSpotify]()
var subscriptions: Set<AnyCancellable> = []
let podsURLComponents = PodsFetcher()
init() {
getToken()
$artistName
.debounce(for: .seconds(2), scheduler: RunLoop.main)
.removeDuplicates()
.compactMap { query in
let url = self.podsURLComponents.makeURLComponentsForSpotify(withName: query, tokenAccess: self.token)
return URL(string: url.string ?? "")
}
.flatMap(fetchDatatesting)
.receive(on: DispatchQueue.main)
.assign(to: \.fetchResult, on: self)
.store(in: &subscriptions)
}
func fetchDatatesting(url: URL) -> AnyPublisher<[PodcastItemsDetailsSpotify], Never> {
URLSession.shared.dataTaskPublisher(for: url)
.map(\.data)
.decode(type: DataResponseSpotify.self, decoder: JSONDecoder())
.map(\.episodes.items)
.replaceError(with: [])
.eraseToAnyPublisher()
}
func getToken() {
let parameters = "grant_type=refresh_token&refresh_token=[example-refresh-token]"
let postData = parameters.data(using: .utf8)
var request = URLRequest(url: URL(string: "https://accounts.spotify.com/api/token")!,timeoutInterval: Double.infinity)
request.addValue("Basic exampleBasicAuth=", forHTTPHeaderField: "Authorization")
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.addValue("inapptestgroup=; __Host-device_id=example_id; __Secure-example=; csrf_token=example", forHTTPHeaderField: "Cookie")
request.httpMethod = "POST"
request.httpBody = postData
URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
if let token = try? decoder.decode(Token.self, from: data) {
DispatchQueue.main.async {
self.token = token.accessToken
}
return
}
}
print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
}.resume()
}
}
发布于 2020-10-23 02:24:43
在不等待的情况下调用设置令牌asynchronously,的getToken
,然后立即尝试创建一个URL,前提是令牌在.compactMap
中可用--到那时还没有可用。
所以,你必须“等待”它,这,结合,你可以做多种方式。
当前最简单(最便宜)的更改是将$token
与$artistName
发布者组合在一起:
$artistName
.debounce(for: .seconds(2), scheduler: RunLoop.main)
.removeDuplicates()
.combineLatest($token.filter { !$0.isEmpty }) // waits for a non-empty token
.compactMap { (query, token) in
var url = ... // construct URL from query and token
return url
}
.flatMap(fetchDatatesting)
.receive(on: DispatchQueue.main)
// I used sink, since assign causes a self retain cycle
.sink { [weak self] result in self?.fetchResult = result }
.store(in: &subscriptions)
但是你真的应该重新设计你的getToken
方法--它写得不好,因为它是一个异步函数,但是它没有一个完成处理程序。
例如,如下所示:
func getToken(_ completion: @escaping (Token) -> Void) {
// set-up, etc..
URLSession.shared.dataTask(with: request) { data, response, error in
// error handling, etc...
if let token = try? decoder.decode(Token.self, from: data) {
completion(token)
}
}.resume()
}
// usage
getToken {
self.token = $0
}
或者,由于您使用的是组合,您可以重写它来返回一个发布者(为了保持简洁,我忽略了错误):
func getToken() -> AnyPublisher<Token?, Never> {
// ...
}
https://stackoverflow.com/questions/64489959
复制相似问题