1

get() 함수의 결과를 tableview에 보내려고합니다. 이 함수 내부의 결과는 Http 게시물에서 가져옵니다. 그래서 nsmutableurl 등을 사용하고 있습니다. 데이터 출력 콘솔에서 볼 수 있고 지금은 내 tableview에 원합니다. 내가 어떻게 할 수 있니?스위프트 : UITableView를 채우는 방법

나는이 코드 묶음을 가지고 있으며 데이터를 가져와 (출력 콘솔에서 볼 수 있음) 이제 테이블 뷰에서이 데이터를로드하려고합니다. 이 데이터를 테이블에 어떻게 전달할 수 있습니까?

func get(){ 

     let request = NSMutableURLRequest(URL: NSURL(string: "http://myurl/somefile.php")!) 
     request.HTTPMethod = "POST" 
     let postString = "id=\(cate_Id)" 
     request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding) 
     let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in 

      guard error == nil && data != nil else {               // check for fundamental networking error 
       print("error=\(error)") 
       return 
      } 

      if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 {   // check for http errors 
       print("statusCode should be 200, but is \(httpStatus.statusCode)") 
       print("response = \(response)") 
      } 

      let responseString = String(data: data!, encoding: NSUTF8StringEncoding) 
      print("responseString = \(responseString)") 
     } 
     task.resume() 
    } 

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     i need the count of the rows here 
    } 



    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     land want to display the data inside each cell 

    } 

답변

0

HTTP 요청 결과에 대한 정보를 제공하지 않으므로 "일반적인 방법"으로 답변하려고합니다.

일반적으로 원하는 데이터의 사전 배열로 응답을받습니다. 쉽게하려면 :의 당신이 문자열을 요청하는 말을하자, 당신은 이런 식으로 할 필요가 : 당신의 HTTP 응답 블록 내

let myStringArray: [String] = [] 

당신은 당신의 응답을 가지고 조심하십시오! 이 코드는 귀하의 응답 트리에 완전히 의존합니다. 당신이 그것을 제공하지 않았기 때문에 나는 당신의 반응을 모릅니다. 당신이 그것을 수행 할 작업에 따라 셀에

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return myStringArray.count 
} 

:

 if let JSON = response.result.value { 

      let myString = String((JSON.valueForKey("stringWithinMyResonseTree"))!) 
      myStringArray.append(myString) 

      self.tableView.reloadData() 
     } 

는 그런 다음에 행 당신의 번호를 가지고있다. 예를 들어 셀 내에 Label이 있고 String 값을 표시하려는 경우 UITableViewCell 하위 클래스를 만들고이를 MyCell이라고 부릅니다. MyCell에서이 같은 레이블의 출구를 만들 :

class MyCell: UITableViewCell { 

    @IBOutlet weak var myLabel: UILabel! 

그런 다음 원하는 문자열로 라벨을 당신의 UITableView 서브 클래스를 돌려 채울 필요가있다.

인터페이스 빌더 속성에서 셀 식별자를 설정하는 것을 잊지 마십시오.

귀하의 요청은 하나의 사전의 배열을 필요로하지만 문자열로 캐스팅합니다. 그래서 대신 get() FUNC의 다음 사용하십시오 :

enter image description here

:

func download() { 
    let requestURL: NSURL = NSURL(string: "http://myurl/somefile.php")! 
    let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL) 
    let session = NSURLSession.sharedSession() 
    let task = session.dataTaskWithRequest(urlRequest) { 
     (data, response, error) -> Void in 

     let httpResponse = response as! NSHTTPURLResponse 
     let statusCode = httpResponse.statusCode 

     if (statusCode == 200) { 
      print("Everyone is fine, file downloaded successfully.") 

      do{ 

       let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments) 

       let grouID = String(json.valueForKey("group_id")) 
       let name = String(json.valueForKey("NAME")) 

       print("grouID = \(grouID)") 
       print("name = \(name)") 
       print("debug: this code is executed") 

      }catch { 
       print("Error with Json: \(error)") 
      } 

     } 
    } 

    task.resume() 
} 

가 문제를 디버깅하려면 예외 중단 점을 만드십시오

관련 문제