AppleAPIを使ってアルバムの情報を取得したい
applemusicAPIを使っているのですが、リクエストができません。
入力した情報が文字化けします
発生している問題・エラーメッセージ
search(term:completion:) URL Session Task Failed unacceptableStatusCode(400)
該当のソースコード
swift
1import UIKit 2 3enum ResponseError: Error { 4 case invalidResponse(URLResponse?) 5 case unacceptableStatusCode(Int) 6} 7 8class APIClient { 9 10 static let imageCache: NSCache<NSString, UIImage> = { 11 let cache = NSCache<NSString, UIImage>() 12 cache.name = "APIClientImage" 13 cache.countLimit = 20 14 cache.totalCostLimit = 10 * 1024 * 1024 15 return cache 16 }() 17 18 static let developerToken = "ディベロッパートークン" 19 20 static let countryCode = "jp" 21 22 func search(term: String, completion: @escaping (SearchResult?) -> Swift.Void) { 23 let completionOnMain: (SearchResult?) -> Void = { searchResult in 24 DispatchQueue.main.async { 25 completion(searchResult) 26 } 27 } 28 29 guard var components = URLComponents(string: "https://api.music.apple.com/v1/catalog/jp/search") else { return } 30 let expectedTerms = term.replacingOccurrences(of: "", with: "+") 31 let urlParameters = ["term": expectedTerms, 32 "limit": "40", 33 "types": "artists,albums"] 34 var queryItems = [URLQueryItem]() 35 for (key, value) in urlParameters { 36 queryItems.append(URLQueryItem(name: key, value: value)) 37 } 38 components.queryItems = queryItems 39 40 print(components.url!) 41 42 var request = URLRequest(url: components.url!) 43 request.httpMethod = "GET" 44 request.setValue("Bearer (APIClient.developerToken)", 45 forHTTPHeaderField: "Authorization") 46 47 data(with: request) { data, error -> Void in 48 guard error == nil else { 49 print(#function, "URL Session Task Failed", error!) 50 completionOnMain(nil) 51 return 52 } 53 54 guard let searchResult = try? JSONDecoder().decode(SearchResult.self, from: data!) else { 55 print(#function, "JSON Decode Failed"); 56 completionOnMain(nil) 57 return 58 } 59 completionOnMain(searchResult) 60 } 61 } 62 63 func album(id: String, completion: @escaping (Resource?) -> Swift.Void) { 64 let completionOnMain: (Resource?) -> Void = { resource in 65 DispatchQueue.main.async { 66 completion(resource) 67 } 68 } 69 70 guard let url = URL(string: "https://api.music.apple.com/v1/catalog/jp/albums/(id)") else { return } 71 72 var request = URLRequest(url: url) 73 request.httpMethod = "GET" 74 request.addValue("Bearer (APIClient.developerToken)", 75 forHTTPHeaderField: "Authorization") 76 77 data(with: request) { data, error -> Void in 78 guard error == nil else { 79 print(#function, "URL Session Task Failed", error!) 80 completionOnMain(nil) 81 return 82 } 83 84 guard let jsonData = try? JSONSerialization.jsonObject(with: data!), 85 let dictionary = jsonData as? [String: Any], 86 let dataArray = dictionary["data"] as? [[String: Any]], 87 let albumDictionary = dataArray.first, 88 let albumData = try? JSONSerialization.data(withJSONObject: albumDictionary), 89 let album = try? JSONDecoder().decode(Resource.self, from: albumData) else { 90 print(#function, "JSON Decode Failed"); 91 completionOnMain(nil) 92 return 93 } 94 completionOnMain(album) 95 } 96 } 97 98 func image(url: URL, completion: @escaping ((UIImage?) -> Void)) { 99 let completionOnMain: (UIImage?) -> Void = { image in 100 DispatchQueue.main.async { 101 completion(image) 102 } 103 } 104 105 if let image = APIClient.imageCache.object(forKey: url.absoluteString as NSString) { 106 print(#function, "image is Cacheed"); 107 completion(image) 108 return 109 } 110 111 data(with: URLRequest(url: url)) { data, error -> Void in 112 guard error == nil else { 113 print(#function, "URL Session Task Failed", error!) 114 completionOnMain(nil) 115 return 116 } 117 118 if let image = UIImage(data: data!) { 119 APIClient.imageCache.setObject(image, forKey: url.absoluteString as NSString) 120 completionOnMain(image) 121 } else { 122 print(#function, "image convert Failed"); 123 completionOnMain(nil) 124 } 125 } 126 } 127} 128 129extension APIClient { 130 func data(with request: URLRequest, completion: @escaping (Data?, Error?) -> Swift.Void) { 131 let task = URLSession.shared.dataTask(with: request) { data, response, error -> Void in 132 guard error == nil else { 133 completion(nil, error) 134 return 135 } 136 137 guard let httpResponse = response as? HTTPURLResponse else { 138 completion(nil, ResponseError.invalidResponse(response)) 139 return 140 } 141 142 guard (200..<300).contains(httpResponse.statusCode) else { 143 completion(nil, ResponseError.unacceptableStatusCode(httpResponse.statusCode)) 144 return 145 } 146 147 completion(data, nil) 148 } 149 task.resume() 150 } 151} 152
試したこと
いろいろ調べたり、しましたが、解決の糸口さえ見つかりません。。。。。
> 入力した情報が文字化けします
ってことですが、どこの箇所のどういうところで、どういうふうに文字化けしてるんでしょうか
https://api.music.apple.com/v1/catalog/jp/search?types=artists,albums&limit=40&term=%E3%81%8D%E3%81%AE%E3%81%93%E5%B8%9D%E5%9B%BD
これが、リクエストのURLなんですが、入力したterm部分が文字化けします
それは文字化けではなくて、パーセントエンコーディングなのでは・・・
あなたの回答
tips
プレビュー