2015-11-17 5 views
0

Я работаю над приложением, которое получает данные из API, который разбит на страницы. Когда пользователь прокручивает, я хочу показать больше данных. Я как бы застрял там, где я сейчас. Вот соответствующий API Service:Paginated API w/Table View

struct APIService { 
private static let baseURL = "api.com" 
private static let clientID = "1234" 
private static let clientSecret = "1234" 

private enum ResourcePath: CustomStringConvertible { 
    case Stream 
    case Community 

    var description: String { 
     switch self { 
     case .Stream: return "/api/posts" 
     } 
    } 
} 

class PostsWrapper { 
    var total_pages: Int? 
    var next_page: Int? 
    var previous_page: Int? 
} 


static func getPosts(page: Int, wrapper: PostsWrapper?, result: ([JSON]) ->()) { 
    getAccessToken() 

    let urlString = baseURL + ResourcePath.Stream.description + "?page=\(page)" 

    let parameters = [ 
     "client_id": clientID, 
     "client_secret": clientSecret, 
    ] 

    Alamofire.request(.GET, urlString, parameters: parameters) 
     .responseJSON { response in 
      if let json = response.result.value { 
       let jsonObj = SwiftyJSON.JSON(json ?? []) 

       if let data = jsonObj["posts"].arrayValue as [SwiftyJSON.JSON]? { 
        let posts = data 
        result(posts) 
       } 

       let wrapper = PostsWrapper() 
       wrapper.next_page = jsonObj["pagination"]["next_page"].int 
       wrapper.previous_page = jsonObj["pagination"]["previous_page"].int 
       wrapper.total_pages = jsonObj["pagination"]["total_pages"].int 

       print(wrapper.total_pages) 

      } 
    } 
} 

} 

Post View Controller:

func loadPosts(page: Int) { 
    APIService.getPosts(1) { (JSON) ->() in 
     self.userStream = JSON 

     self.tableView!.reloadData() 

     Loading.stop() 

    } 
} 

Любое направление будет иметь в виду, чтобы загрузить следующую страницу сообщений и шоу в виде таблицы.

ответ

1

Вам необходимо проверить состояние методов willDisplayCell, как показано ниже

override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { 
      if indexPath.row == <YOUR_ARRAY>.count - 1 { // need to check some extra condition like all data loaded 
      //call API here 
      //after response from API add you new records to your array and use insertRowsAtIndexPaths method to insert new rows to table 
      } 
    } 
+0

Почему вы добавляете -1 при проверке indexPath.row? – user2722667