2017-09-04 1 views
-1

그래서 서버에서 일부 json 데이터를 받으면 배열로 저장하려고하므로 tableview를 채울 수 있지만 문제가 발생했습니다. 내 코드 :구문 분석 된 json 데이터를 신속하게 배열에 저장하는 방법

class UserInfo : UIViewController{ 
var main = "" 
session.dataTask(with: url) { (data, response, error) in 
     if let response = response { 
      print (response) 
     } 
     if let data = data { 
      let json = (try? JSONSerialization.jsonObject(with: data, options: [])) 
      print(json) 
      guard let array = json as? [Any] else {return} 
      for info in array { 
      guard let infoDict = info as? [String : Any] else{return} 
      //there is a declared var called main 
      //main is the one i want save as an array, currently its a variable. i tried to save it as an array by using as! Array but i get error 
      self.main = infoDict["Title"] as! String 
      print (self.main) 
} 
} 
}.resume() 
} 
+0

수신 한 json을 게시해야 Google에서 어떤 데이터를 처리하는지 알 수 있습니다. – ovidiur

+0

"하지만 오류가 발생합니다."어떤 오류가 있습니까? – Larme

+0

이러한 데이터를 UserDefaults에 저장 하시겠습니까? – shahnilay86

답변

1

먼저 범위 ary을 선언해야합니다. 그런 다음 데이터를 동일한 ary에 저장해야합니다.

var ary: NSMutableArray = NSMutableArray() 

session.dataTask(with: url) { (data, response, error) in 
      if let response = response { 
       print (response) 
      } 
      if let data = data { 
       let json = (try? JSONSerialization.jsonObject(with: data, options: [])) 
       print(json) 
       guard let array = json as? [Any] else {return} 
       for info in array { 
        guard let infoDict = info as? [String : Any] else{return} 
        //there is a declared var called main 
        //main is the one i want save as an array, currently its a variable. i tried to save it as an array by using as! Array but i get error 
        self.main = infoDict["Title"] as! String 
        self.ary.add(self.main) 
        print (self.main) 
       } 
       print("Final array is :::",self.ary) 
      } 
      }.resume() 

위 코드를 시도해보십시오. 희망이 당신을 위해 작동합니다.

+0

잘 작동하지만이 "인쇄 ("최종 배열은 ::: "self.ary" "self"를 추가했습니다. " –

+0

@ Duck.P 예, 죄송합니다. 서버에서 데이터를 가져 오는 요청을 처리하는 클로저이기 때문에 감사합니다. – shahnilay86

+0

FUNC에있는 tableView (_있는 tableView : jQuery과, cellForRowAt indexPath : IndexPath) ->있는 UITableViewCell { 세포 =있는 UITableViewCell하자? (스타일 : UITableViewCellStyle.default, reuseIdentifier을 "셀") ​​ cell.textLabel는 .text =이 배열 // 때 (cell.textlable? .text = arry)return (cell) } –

관련 문제