I have a json url that supports pagination.
My question is how can i parse this paginations page with using alamofire and swiftyjson ?
my json url like :
{
"meta":{
"code":200
},
"data":{ },
"pagination":{
"total":86,
"totalPages":3,
"page":1,
"nextPage":2,
"nextPageUrl":"http://.............?page=2"
}
}
** !!!!!!! UPDATE !!!!!!!**
my code like this but i get some exception :
func GetDataFromUrl(from:String){
Alamofire.request(from, method: .get).validate().responseJSON { response in
switch response.result {
case .success(let value):
let json = JSON(value)
self.storeData = [PopulerMagazalarData]()
//...Creating Data Obj.
let data = PopulerMagazalarData()
let username = json["data"]["store"]["user"]["username"].string
let userpic = json["data"]["store"]["user"]["profilePicture"].string
let productsCount = json["data"]["store"]["productsCount"].int
let description = json["data"]["store"]["description"].string
let followedby = json["data"]["store"]["user"]["counts"]["followedBy"].int
let totalPage = json["pagination"]["totalPages"].int
let count:Int? = json["data"]["products"].array?.count
if let ct = count {
for index in 0...ct-1{
let datas = PopulerMagazalarData()
let images = json["data"]["products"][index]["images"]["standart"]["url"].string
datas.img1 = images
self.storeData.append(datas)
}
}
//*****************
data.username = username
data.profilPic = userpic
data.producsCount = productsCount
data.desc = description
data.followedby = followedby
//******************
self.storeData.append(data)
for index in 2 ... totalPage! {
self.GetDataFromUrl(from: "https://api......../store/\(username!)?page=\(index)")
}
// for refresh collecitonView
self.refresh_now()
case .failure(let error):
print(error)
}
}
}
//...CollectionView ReloadData func...
func refresh_now(){
DispatchQueue.main.async (
execute:
{
self.MyStoreCollectionView.reloadData()
}
)
}
but when i scroll my app get down .
// make the request with Alamofire
Alamofire.request("myUrl").response { response in
// to create the SwiftyJSON object
let json = JSON(data: response.data!)
// get the values from the json response
let code = json["meta"]["code"].int
let total = json["pagination"]["total"].int
}
Related
I am using shopify iOS SDK(mobile-buy-sdk-ios) in react native to get login user's orders.
Here is my code,
let query = Storefront.buildQuery { $0
.customer(customerAccessToken: token) { $0
.orders(first: count, reverse: true) { $0
.edges { $0
.node { $0
.id()
.orderNumber()
.totalPrice()
.statusUrl()
.lineItems(first: 25){ $0
.edges{ $0
.node{ $0
.title()
.quantity()
.variant{ $0
.id()
.price()
.title()
.image{ $0
.originalSrc()
}
}
}
}
}
let task = self.client.queryGraphWith(query, cachePolicy: .networkOnly) { response, error in
error.debugUserPrint()
let userOrders = response.customer?.orders.edges[0].node;
let res = try! JSONSerialization.data(withJSONObject: userOrders)
completion([res])
}
And I am getting this response in userOrders variable
<QueryRoot: ["customer": {
orders = {
edges = (
{
node = {
id = "Z2lkOi8vc2hvcGlmeS9PcmRlci8yMjY2NTM3NzU0NzEwP2tleT0zNWFiYzBkMjRmMDk3MjZlYzgzYjkwZDVlZGI5YjM4MA==";
lineItems = {
edges = (
{
node = {
quantity = 1;
title = "Gift wrapping";
variant = {
id = "Z2lkOi8vc2hvcGlmeS9Qcm9kdWN0VmFyaWFudC8xMjE3MzkzNjYyMzcwMg==";
image = {
originalSrc = "https://cdn.shopify.com/s/files/1/2331/3377/products/Gift_Boxes_11_22_2017_Standard_1024x1024_60d01a1c-f665-4c9e-b80b-f6fda9167de3.jpg?v=1521444032";
};
price = "10.00";
title = "Default Title";
};
};
}
);
};
orderNumber = 1040;
statusUrl = "23313377/orders/11f378e7df2731521429f377015d2ec2/authenticate?key=35abc0d24f09726ec83b90d5edb9b380";
totalPrice = "10.00";
};
}
);
};
}]>)
this formate, so try to parse this data to JSON object to pass data from iOS function to javascript function. I have tried
JSONSerialization.data(withJSONObject: userOrders)
but it is not working. I just want to parse this data to JSON. I have also tried many other ways but no luck.
Thanks.
They're a number of ways I can think of...
Alamofire if you have access to that query endpoint
Alamofire.request("http://feeds.news24.com/articles/Fin24/Tech/rss").responseJSON { json in
/// do what you want with your json
}
No endpoint, use SwiftyJSON
let json = JSON(data: dataFromNetworking)
if let userName = json[0]["user"]["name"].string {
//Now you got your value
}
I don't think there is straightforward way to get JSON, using mobile-buy-sdk. However you can convert response to JSON
if let data = try? JSONSerialization.data(withJSONObject: userOrders.fields, options: .prettyPrinted) {
print(String(data: data, encoding: .utf8))
}
I have been trying to get the below code to return an array of information that can use in a UIPickerView class "title for Rows. The code does not work, I do now that when I run the print script it does return a list of all the values from my JSON values. A sample of parsed JSON. I have been watching YouTube Videos and reading info about this for two evenings now. Any help would be great. Everything I find sends Parsed JSON results to a table view.
{
date = "2017-05-01";
"financial_institution" = "Your Neighbourhood C.U.";
"five_year" = "2.79";
"four_year" = "3.15";
key = 86;
"one_year" = "2.79";
"six_months" = 0;
"three_year" = "3.09";
"two_year" = "2.89";
"variable_rate" = 0;
}
)
func getJSONData()
{
let url = URL(string:"")
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil {
print("error")
}
else {
if let mydata = data {
do {
let myJson = try JSONSerialization.jsonObject(with: mydata, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
print(myJson)
var lenderName = myJson["financial_institution"]
for i in lenderName {
var lender = "financial_institution"
lender += "\(i)"
var lenderList = myJson[lender].string as String!
lenderNamesArray.append(lenderList)
}
}
catch {
// catch error
}
}
}
}
task.resume()
}
I'm making a weather app using OpenweatherAPI. I download data from web, but when I want to pass it to another class it show as nil. Here is the code:
So that's the class I'm getting data from the API
var currentTemp: Double {
if _currentTemp == nil {
_currentTemp = 120.0
}
return _currentTemp
}
func downloadWeatherDetails(completed: #escaping DownloadComplete) {
Alamofire.request(CURRENT_WEATHER_URL).responseJSON { response in
let result = response.result
if let dict = result.value as? Dictionary<String, Any> {
if let main = dict["main"] as? Dictionary<String, Any> {
if let currentTemperature = main["temp"] as? double_t {
let kelvinToCelsiusPreDivision = (currentTemperature - 273.15)
let kelvinToCelsius = Double(round((10 * kelvinToCelsiusPreDivision) / 10))
self._currentTemp = kelvinToCelsius
print(self._currentTemp)
}
}
}
completed()
} }
And the mainVC - ViewController:
func updateMainUI() {
currentTempLabel.text = "\(currentWeather.currentTemp)"
}
I'm of course calling updateMainUI in ViewDidLoad, but IMHO I think the method that updates UI is probably called before getting the data from the JSON.
The Label on the App shows 120 - so it is considered as nil...
Sorry about parenthesis if there is something wrong.
Thanks for help in advice :)
EDIT:
Ohh and I forgot to add.. The data from API is perfectly fine, so the call to API is working :)
// I Hope that helps
func downloadWeatherDetails(completed: #escaping DownloadComplete) {
//Download Current Weather Data
Alamofire.request(CURRENT_WEATHER_URL).responseJSON { response in
let result = response.result
if let dict = result.value as? Dictionary<String, AnyObject> {
if let main = dict["main"] as? Dictionary<String, AnyObject> {
if let currentTemperature = main["temp"] as? Double {
let kelvinToFarenheitPreDivision = (currentTemperature * (9/5) - 459.67)
let kelvinToFarenheit = Double(round(10 * kelvinToFarenheitPreDivision/10))
self._currentTemp = kelvinToFarenheit
print(self._currentTemp)
}
}
}
completed()
}
}
I am very beginner in swift and I am trying to fetch some JSON Data from an api and then creating an array from that Data.
Alamofire.request(.GET, URL)
.responseJSON
{
response in
let JSON = response.result.value
let response = JSON as! NSDictionary
let Data = response.objectForKey("data")!
for slot in timeSlot as! NSDictionary
{
let json = slot.value
let availability = json as! NSDictionary
let myavailable = availability.objectForKey("available")!
let slotTime = availability.objectForKey("time")!
if (myavailable as! NSNumber == 1)
{
self.fetchSlot.append(slotTime as! String)
}
}
for x in self.mySlot
{
for c in self.fetchSlot
{
if (c == x)
{
self.availableSlot.append(x)
}
}
}
}
Now I am trying to print the "self.availableslot" in the same viewDid load function.
But it always returning an empty array, because it is compiling before all the JSON data is fetched.
Please if there is any way how can I use reload method or completion handler kind of things to get my job done.
func performAlamoFireRequest(completion: () -> Void) {
Alamofire.request(.GET, URL).responseJSON {
response in
let JSON = response.result.value
let response = JSON as! NSDictionary
let Data = response.objectForKey("data")!
for slot in timeSlot as! NSDictionary {
let json = slot.value
let availability = json as! NSDictionary
let myavailable = availability.objectForKey("available")!
let slotTime = availability.objectForKey("time")!
if (myavailable as! NSNumber == 1) {
self.fetchSlot.append(slotTime as! String)
}
}
for x in self.mySlot {
for c in self.fetchSlot {
if (c == x) {
self.availableSlot.append(x)
}
}
}
completion()
}
}
performAlamoFireRequest() {
//code to perform after here
}
I have aded HMSegmentedControl to make a swiping segmented control in my iOS app.I am loading all the data initially because then it will facilitate the scrolling. So I have to load several tables under several categories. Category name is the segmented control item title. So this is how I set my titles.
for(var i=0; i<dm.TableData.count; i++)
{
self.array.append(dm.TableData[i]["name"] as! String)
}
segmentedControl.sectionTitles=self.array
Categories are loading according to the order of this array without any issue. Then I am loading my tables like this.
for i in 0..<dm.TableData.count {
self.catID=self.dm.TableData[i]["term_id"] as? String
switch self.catID {
case "55":
self.jsonParser()
case "1":
self.getBusiness()
case "2":
self.getNews()
case "4":
self.getSports()
case "5":
self.getEntertainment()
case "57":
self.getCrime()
case "21":
self.getPolitics()
case "28":
self.getWorld()
case "89":
self.getVideos()
case "111":
self.getLocalNews()
default:
print("Default")
}
}
This is my jsonParser method. getBusiness(),getNews(),getSports() all those methods are just same as this and load to seperate array and the dictionary key is different.
func jsonParser() {
let urlPath = "http://www.li67t8.lk/mobileapp/news.php?"
let category_id=self.catID
let catParam="category_id"
let strCatID="\(catParam)=\(category_id)"
let strStartRec:String=String(startRec)
let startRecPAram="start_record_index"
let strStartRecFull="\(startRecPAram)=\(strStartRec)"
let strNumOfRecFull="no_of_records=10"
let fullURL = "\(urlPath)\(strCatID)&\(strStartRecFull)&\(strNumOfRecFull)"
print(fullURL)
guard let endpoint = NSURL(string: fullURL) else {
print("Error creating endpoint")
return
}
let request = NSMutableURLRequest(URL:endpoint)
NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) in
do {
guard let data = data else {
throw JSONError.NoData
}
guard let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? NSDictionary else {
throw JSONError.ConversionFailed
}
print(json)
if let countries_list = json["data"] as? NSArray
{
// for (var i = 0; i < countries_list.count ; i++ )
for i in 0..<countries_list.count
{
if let country_obj = countries_list[i] as? NSDictionary
{
//self.TableData.append(country_obj)
self.breakingNews.append(country_obj)
}
}
dispatch_async(dispatch_get_main_queue()) {
print("%%%%%%%%%%% CAT ID %%%%%%%%%% \(self.catID)")
if let checkedUrl = NSURL(string: self.breakingNews[0]["thumb_url"] as! String) {
self.imageURL=checkedUrl
}
if let time = self.breakingNews[0]["duration"] as? String
{
self.timeDuration=time
}
if let likes = self.breakingNews[0]["read_count"] as? String
{
self.noOfLikes=likes
}
if let title = self.breakingNews[0]["post_title"] as? String
{
self.titleNews=title
}
self.addedArray.append("Breaking News")
self.commonData["Breaking News"]=self.breakingNews
self.updateUI()
print("-------BREAKING--------")
}
}
} catch let error as JSONError {
print(error.rawValue)
} catch let error as NSError {
print(error.debugDescription)
}
}.resume()
}
I have one method for UpdateUI() and it creates UITableView dynamically and assign tag value dynamically (I keep an Int called index and I assign that index to tableview tag and after adding table to super view I increment the index count by 1)
According to this I get data and load to the tableview. But my problem is data not getting in the same order I call to those methods. As an example jsonParser() returns its data set and then it returns getSportsData() data. like wise my data not according to the segment title order.
So how can I solve this problem? Please help me.
Thanks