2016-11-01 7 views
0

このメソッドを使用してHTTPリクエストを行い、キーと値を正常に返します。成功したHTTPリクエストの後、値を保存してTableViewに表示する方法

let url = NSURLRequest(URL: NSURL(string: "api.com")!) 

let request : NSMutableURLRequest = NSMutableURLRequest() 

let task = URLSession.shared.dataTask(with: request as URLRequest) { 
     data, response, error in 

     if error != nil 
     { 
      print("error=\(error)") 
      return 
     } 

     let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) 
     print("responseString = \(responseString)") 

     do { 
      if let convertedJsonIntoDict = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary 

は、私がテーブルビューで表示するため、変数として格納する必要がある2つの文字列としてJSON、「タイトル」からキー、URLなどの「バナー」があります。どのように値を保存できますか?私は多くの解決策を探しましたが、うまくいきません。

JSON出力

"promotion":[ 
    { 

    "title":"4G LTE", 
    "banner":"imageurl" 
    }, 
+0

jsonの出力を共有してください。 – Profstyle

+0

@Profstyleを更新しました – hatched

+0

あなたはenumを作成できます –

答えて

2

私はstructに保管することをお勧めします。これは次のようなものです:

struct Promotion { 
    let title: String 
    let banner: String 

    init(dictionary: [String: AnyObject]) { 
     title = dictionary["title"] as? String ?? "" 
     banner = dictionary["banner"] as? String ?? "" 
    } 
} 

ご覧のとおり、それに辞書を送ることができます。私はconvertedJsonIntoDict行の後に起こることができない何ができますが、以下のこのstructを使用することができます。このことができます

// Create a container for storing the promotions 
var promotions: [Promotion] = [] 
// Iterate through every dictionary 
for dictionary in convertedJsonIntoDict { 
// Create a promotion 
    let promotion = Promotion(dictionary: dictionary as [String : AnyObject]) 
    promotions.append(promotion) 
} 
// Check what do you have in promotions 
print(promotions) 

願っています!

関連する問題