質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.51%
JSON

JSON(JavaScript Object Notation)は軽量なデータ記述言語の1つである。構文はJavaScriptをベースとしていますが、JavaScriptに限定されたものではなく、様々なソフトウェアやプログラミング言語間におけるデータの受け渡しが行えるように設計されています。

Xcode

Xcodeはソフトウェア開発のための、Appleの統合開発環境です。Mac OSXに付随するかたちで配布されています。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

Q&A

解決済

1回答

3087閲覧

[Swift3] 複数のJSONを日付順に並び替えたい

userA

総合スコア8

JSON

JSON(JavaScript Object Notation)は軽量なデータ記述言語の1つである。構文はJavaScriptをベースとしていますが、JavaScriptに限定されたものではなく、様々なソフトウェアやプログラミング言語間におけるデータの受け渡しが行えるように設計されています。

Xcode

Xcodeはソフトウェア開発のための、Appleの統合開発環境です。Mac OSXに付随するかたちで配布されています。

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

0グッド

0クリップ

投稿2016/12/06 18:21

現在複数のサイトを利用してRSSリーダーを作成しているのですが、日付順に並び替えるためソートしたのですが1つのJSONの日付順、1つのJSONの日付順と個々にソートされて表示されてしまいます。
これを4つのJSONの日付順に表示したいのですがどうすれば良いかわかりません。
どなたかご教授していただけると幸いです。
以下コード

var NewDataArray = NSMutableArray() var myTableView : UITableView! var URL = "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q=表示したいRSS" var URL2 = "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q=表示したいRSS" var URL3 = "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q=表示したいRSS" var URL4 = "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q=表示したいRSS" var isLoading : Bool = false override func viewDidLoad() { super.viewDidLoad() let nib:UINib = UINib(nibName: "ItemCell", bundle: nil) self.myTableView.register(nib, forCellReuseIdentifier: "ItemCell") RSSArray() } func RSSArray() { getRSS() getRSS0() getRSS1() getRSS2() } func getRSS() { if let requestURL = Foundation.URL(string: URL) { Alamofire.request(requestURL, method: .get , parameters: nil).responseJSON { response in if response.result.isSuccess { let jsonDic = response.result.value as! NSDictionary let responseData = jsonDic["responseData"] as! NSDictionary let feed = responseData["feed"] as! NSDictionary if let entries = feed["entries"] as? NSArray { let timeArray : NSMutableArray = [] for i in 0..<entries.count { let dic = entries[i] as! NSDictionary let title = dic["title"] as! String let content = dic["content"] as! String let links = dic["link"] as! String let publishedDate = self.convertDateFormat(dic["publishedDate"] as! String) self.timeArray[i] = ["title": title,"link": links,"content": content, "publishedDate": publishedDate] } //publisheDateでソート let sd = NSSortDescriptor(key: "publishedDate", ascending: false) let sorted = self.timeArray.sortedArray(using: [sd]) as NSArray self.NewDataArray.addObjects(from: sorted as! [Any]) //self.NewDataArray = self.sortDate(entries, isAscending: false) DispatchQueue.main.async { self.myTableView.reloadData() } } } } } } //etc...... func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return NewDataArray.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // 再利用するCellを取得する. let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath) as! ItemCell let Newdic = NewDataArray[indexPath.row] as! NSDictionary let title = Newdic["title"] as! String let publishedDate = Newdic["publishedDate"] as! String let links = Newdic["link"] as! String let contents = Newdic["content"] as! String let timedate = publishedDate cell.backgroundColor = UIColor(red: 250/255, green: 250/255, blue: 250/255, alpha: 1) let selectCell = UIView() selectCell.backgroundColor = UIColor.lightGray cell.selectedBackgroundView = selectCell cell.title.text = title cell.time.text = timedate return cell } //日付を変換 func convertDateFormat(_ dateStr:String) -> String { // 引数で渡ってきた文字列をNSDateFormatterでNSDateに直します let inFormatter = DateFormatter() inFormatter.locale = Locale(identifier: "en_US_POSIX") inFormatter.dateFormat = "E, dd MMM yyyy HH:mm:ss Z" let date:Date = inFormatter.date(from: dateStr)! // NSDateから指定のフォーマットの文字列に変換します let outFormatter = DateFormatter() outFormatter.dateFormat = "yyyy/MM/dd HH:mm" return outFormatter.string(from: date) }

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

fromageblanc

2016/12/06 18:33

複数あるRSSのデータ構造は同じなのですか?項目名とか
userA

2016/12/06 19:18

googleのAPIを使っているので全て同じです。
fromageblanc

2016/12/06 20:51

だったらけっこう簡単じゃないですか。何がネックになってるのですか?
userA

2016/12/06 21:29

どういう訳かこのコードで表示させると、ソートされたRSS(A)の次にRSS(B)、RSS(C)と表示されてしまうんです。理想ではソートされたRSS(A,B,C)で表示されるのが理想なのですが。。。説明が下手で申し訳ありませんm(_ _)m
fromageblanc

2016/12/06 21:45

いやいや、質問の意図は伝わってますよ。AとBとCをマージした後ソートすればOKだと思うんですが... ソートの方法はもう解決してますし。
userA

2016/12/06 21:47

失礼いたしましたm(_ _)m そうなるとたぶんマージ出来てないんだと思うんですけど表現方法がわからないんですよね。。。。。
guest

回答1

0

ベストアンサー

ループと非同期処理の連携はここを参考にさせてもらいました.
http://qiita.com/kazuhirox/items/9ecb25bc238ad2d47ff0

rssUrls配列のデータを変更してください.
変数名の頭が大文字だったり小文字だったりが気になりつつもuserAさんの原本を尊重してます...

swift

1 2// Swift3.0 Alamofire4.2.0 3 4import UIKit 5import Alamofire 6 7class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource { 8 9 @IBOutlet weak var myTableView :UITableView! 10 11 var NewDataArray : NSMutableArray = [] 12 var timeArray : NSMutableArray = [] 13 14 // RSS取得URLをここに列挙 15 var rssUrls:[String] = [ 16 "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=50&q=https://goo.gl/6E1EPK", 17 "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=50&q=https://goo.gl/6E1EPK", 18 "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=50&q=https://goo.gl/6E1EPK" 19 ] 20 21 override func viewDidLoad() { 22 super.viewDidLoad() 23 24 myTableView.delegate = self 25 myTableView.dataSource = self 26 27 //RSSArray() 28 getRSS() 29 } 30 31 override func didReceiveMemoryWarning() { 32 super.didReceiveMemoryWarning() 33 // Dispose of any resources that can be recreated. 34 } 35 36 37// func RSSArray() { 38// getRSS() 39// } 40 41 func getRSS() { 42 43 var index:Int = 0 // NewDataArrayのインデックス 44 var keepAlive = true // 待機フラグ 45 46 for j in 0 ..< rssUrls.count { 47 48 keepAlive = true 49 50 if let requestURL = Foundation.URL(string: rssUrls[j]) { 51 52 Alamofire.request(requestURL, method: .get , parameters: nil).responseJSON { 53 response in 54 if response.result.isSuccess { 55 let jsonDic = response.result.value as! NSDictionary 56 let responseData = jsonDic["responseData"] as! NSDictionary 57 let feed = responseData["feed"] as! NSDictionary 58 if let entries = feed["entries"] as? NSArray { 59 60 for i in 0..<entries.count { 61 let dic = entries[i] as! NSDictionary 62 let title = dic["title"] as! String 63 let content = dic["content"] as! String 64 let links = dic["link"] as! String 65 let publishedDate = self.convertDateFormat(dic["publishedDate"] as! String) 66 67 self.timeArray[index] = ["title": title,"link": links,"content": content, "publishedDate": publishedDate] 68 index += 1 69 } 70 } 71 } 72 73 keepAlive = false 74 } 75 } 76 77 // Alamofireの非同期処理をここで待機 78 let runLoop = RunLoop.current 79 while keepAlive && 80 runLoop.run(mode: RunLoopMode.defaultRunLoopMode, before: NSDate(timeIntervalSinceNow: 0.1) as Date) { 81 // 0.1秒毎の処理なので、処理が止まらない 82 } 83 84 // 次のRSSへ 85 86 } 87 88 //publisheDateでソート 89 let sd = NSSortDescriptor(key: "publishedDate", ascending: false) 90 let sorted = self.timeArray.sortedArray(using: [sd]) as NSArray 91 92 self.NewDataArray = sorted.mutableCopy() as! NSMutableArray 93 94 } 95 96 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 97 return NewDataArray.count 98 } 99 100 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 101 102 // 再利用するCellを取得する. 103 let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath) as! ItemCell 104 105 let Newdic = NewDataArray[indexPath.row] as! NSDictionary 106 let title = Newdic["title"] as? String 107 let publishedDate = Newdic["publishedDate"] as? String 108 let links = Newdic["link"] as! String 109 let content = Newdic["content"] as! String 110 let timedate = publishedDate //self.convertDateFormat(publishedDate!) 111 cell.title.text = title 112 cell.time.text = timedate 113// cell.webimage.image = UIImage(named: "") 114 115 return cell 116 } 117 //日付を変換 118 func convertDateFormat(_ dateStr:String) -> String { 119 // 引数で渡ってきた文字列をNSDateFormatterでNSDateに直します 120 let inFormatter = DateFormatter() 121 inFormatter.locale = Locale(identifier: "en_US_POSIX") 122 inFormatter.dateFormat = "E, dd MMM yyyy HH:mm:ss Z" 123 let date:Date = inFormatter.date(from: dateStr)! 124 // NSDateから指定のフォーマットの文字列に変換します 125 let outFormatter = DateFormatter() 126 outFormatter.dateFormat = "yyyy/MM/dd HH:mm" 127 return outFormatter.string(from: date) 128 } 129 130} 131

投稿2016/12/07 17:01

fromageblanc

総合スコア2724

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

userA

2016/12/09 06:30

本当に助かりましたありがとうございます!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.51%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問