Mapping two kind of responses with Alamofire and AlamofireObjectMapper (iOS - swift) - ios

So, I'm making an iOS app the search a movie on imdb database (using omdb api) and the user could save the favorites.
To search by imdbTitle the request url is "https://www.omdbapi.com/?s=(imdbTitle)&type=movie", if imdbTitle = "arq", for example, the response is:
{
Response = True;
Search = (
{
Poster = "https://images-na.ssl-images-amazon.com/images/M/MV5BMjAxODQ2MzkyMV5BMl5BanBnXkFtZTgwNjU3MTE5OTE#._V1_SX300.jpg";
Title = ARQ;
Type = movie;
Year = 2016;
imdbID = tt5640450;
},
{
Poster = "N/A";
Title = Arq;
Type = movie;
Year = 2011;
imdbID = tt2141601;
},
{
Poster = "N/A";
Title = "A.R.Q.";
Type = movie;
Year = 2015;
imdbID = tt3829612;
}
);
totalResults = 3;
}
But for save the movie I have to search by imdbID, url: "https://www.omdbapi.com/?i=(imdbID)", if imdbID is the one from the movie searched, imdbID = tt3829612, and the response is:
{
Actors = "Robbie Amell, Rachael Taylor, Shaun Benson, Gray Powell";
Awards = "N/A";
BoxOffice = "N/A";
Country = "USA, Canada";
DVD = "16 Sep 2016";
Director = "Tony Elliott";
Genre = "Sci-Fi, Thriller";
Language = English;
Metascore = "N/A";
Plot = "Trapped in a lab and stuck in a time loop, a disoriented couple fends off masked raiders while harboring a new energy source that could save humanity.";
Poster = "https://images-na.ssl-images-amazon.com/images/M/MV5BMjAxODQ2MzkyMV5BMl5BanBnXkFtZTgwNjU3MTE5OTE#._V1_SX300.jpg";
Production = Netflix;
Rated = "N/A";
Ratings = (
{
Source = "Internet Movie Database";
Value = "6.4/10";
},
{
Source = "Rotten Tomatoes";
Value = "60%";
}
);
Released = "16 Sep 2016";
Response = True;
Runtime = "88 min";
Title = ARQ;
Type = movie;
Website = "N/A";
Writer = "Tony Elliott";
Year = 2016;
imdbID = tt5640450;
imdbRating = "6.4";
imdbVotes = "17,481";
}
So, my Movie class has to have the following attributes: poster, title, runtime, genre, director, actors, plot, released, imdbID and imdbRating (to show this on my UI View, except the imdbID, of course)
I'm a beginner and I'm too confused by all those things (never worked with API data before).
Anyways, after a lot of search I found that there is a way to get this response as an Array using AlamofireObjectMapper.
I already have my request functions:
func searchMoviesOnJson(imdbTitle: String, completionHandler: #escaping (Dictionary<String, Any>?) -> ()) {
let urlByName: String = "https://www.omdbapi.com/?s=\(imdbTitle)&type=movie"
//returns a list of movies that contains the title searched
//------------------------------------------------
Alamofire.request(urlByName).responseJSON {
response in
switch response.result {
case .success(let value):
let moviesJSON = value
completionHandler(moviesJSON as? Dictionary<String, Any>)
case .failure(_):
completionHandler(nil)
}
}
//------------------------------------------------
}
func getMovieFromJson(imdbID: String, completionHandler: #escaping (Dictionary<String, String>) -> ()) {
let urlById: String = "https://www.omdbapi.com/?i=\(imdbID)"
//returns a single movie information
//------------------------------------------------
Alamofire.request(urlById).responseJSON {
response in
if let moviesJSON = response.result.value {
completionHandler(moviesJSON as! Dictionary<String, String>)
}
}
//------------------------------------------------
}
So, could anyone explain to me (like you'll explain to a child) how can I do this mapping? I created a Movie.swift and in this file I'll put my class Movie and class MovieDAO.
How can I implement this two classes using AlamofireObjectMapper and who I have to change in my request methods?
Update:
class Movie {
let poster: String?
let title: String?
let runtime: String?
let genre: String?
let director: String?
let actors: String?
let plot: String?
let released: String?
let imdbID: String?
let imdbRating: String?
init(poster: String?, title: String?, runtime: String?, genre: String?, director: String?, actors: String?, plot: String?, released: String?, imdbID: String?, imdbRating: String?) {
//checking if is nil
if let isPoster = poster {
self.poster = isPoster
} else {
self.poster = nil
}
if let isTitle = title {
self.title = isTitle
} else {
self.title = nil
}
if let isGenre = genre {
self.genre = isGenre
} else {
self.genre = nil
}
if let isRuntime = runtime {
self.runtime = isRuntime
} else {
self.runtime = nil
}
if let isDirector = director {
self.director = isDirector
} else {
self.director = nil
}
if let isActors = actors {
self.actors = isActors
} else {
self.actors = nil
}
if let isPlot = plot {
self.plot = isPlot
} else {
self.plot = nil
}
if let isReleased = released {
self.released = isReleased
} else {
self.released = nil
}
if let isImdbID = imdbID {
self.imdbID = isImdbID
} else {
self.imdbID = nil
}
if let isImdbRating = imdbRating {
self.imdbRating = isImdbRating
} else {
self.imdbRating = nil
}
}
}
UPDATE 2
I declare the variable movieDetail as you said to do, but the xcode showed an error and suggesting that I could add the parameters, so I did and its not solved.

You will have to parse the JSON received:
For e.g. if json received is:
{
Response = True;
Search = (
{
Poster = "https://images-na.ssl-images-amazon.com/images/M/MV5BMjAxODQ2MzkyMV5BMl5BanBnXkFtZTgwNjU3MTE5OTE#._V1_SX300.jpg";
Title = ARQ;
Type = movie;
Year = 2016;
imdbID = tt5640450;
},
{
Poster = "N/A";
Title = Arq;
Type = movie;
Year = 2011;
imdbID = tt2141601;
},
{
Poster = "N/A";
Title = "A.R.Q.";
Type = movie;
Year = 2015;
imdbID = tt3829612;
}
);
totalResults = 3;
}
As you have mentioned, if you have stored the json response in NSDictionary
You can access the values of Search results as
var moviesArray = [Movie]() //array of your Movie class
var imdbIdArray = [String]()
if let searchResults = moviesJSON["Search"] as? NSArray {
for searchResult in searchResults {
let movieResult = searchResult as! Dictionary<String,String>
let movieDetail = Movie()
movieDetail.title = movieResult["Title"]
movieDetail.type = movieResult["Type"]
//similarly you can do it for other params as well
moviesArray.append(movieDetail)
let imdbId = movieResult["imdbId"]
imdbIdArray.append(imdbId)
}
}
class Movie: NSObject {
var title = String()
var type = String()
}
Now moviesArray consist of list of movies returned in the result set.

Related

Parsing a JsonObject in Swift 4 from an URL

It seems for me this is a very simple task, but even after a lot of researching and trying I can't get it working...
So I have for example this URL, for what I understand this is a api to an JSONObject?!
http://api.geekdo.com/api/images?ajax=1&gallery=all&nosession=1&objectid=127023&objecttype=thing&pageid=357&showcount=1&size=thumb&sort=recent
If I open this link in my browser I get the following result:
{"images":[{"imageid":"1567153","imageurl_lg":"https://cf.geekdo-images.com/images/pic1567153_lg.jpg","name":null,"caption":"White
power
tiles","numrecommend":"6","numcomments":"0","user":{"username":"manosdowns","avatar":"1","avatarfile":"avatar_id33829.jpg"},"imageurl":"https://cf.geekdo-images.com/6fCr14v025ZKYhXRMnbhYR16Ta8=/fit-in/200x150/pic1567153.jpg"}],"config":{"sorttypes":[{"type":"hot","name":"Hot"},{"type":"recent","name":"Recent"}],"numitems":402,"endpage":402,"galleries":[{"type":"all","name":"All"},{"type":"game","name":"Game"},{"type":"people","name":"People"},{"type":"creative","name":"Creative"}],"categories":[{"type":"","name":"All"},{"type":"BoxFront","name":"BoxFront"},{"type":"BoxBack","name":"BoxBack"},{"type":"Components","name":"Components"},{"type":"Customized","name":"Customized"},{"type":"Play","name":"Play"},{"type":"Miscellaneous","name":"Miscellaneous"},{"type":"Mature","name":"Mature"},{"type":"uncat","name":"Uncategorized"}],"licensefilters":[{"type":"","name":"Any"},{"type":"reuse","name":"Copying
allowed"},{"type":"commercial","name":"Commercial use
allowed"},{"type":"modify","name":"Modification
allowed"}],"datefilters":[{"value":"alltime","name":"All
Time"},{"value":"today","name":"Today"},{"value":"twodays","name":"Two
Days"},{"value":"last7","name":"Last 7
Days"},{"value":"last30","name":"Last 30
Days"},{"value":"year","name":"Last 365
Days"}],"filters":[{"name":"Licenses","listname":"licensefilters","type":"licensefilter"},{"name":"Category","listname":"categories","type":"tag"},{"name":"Gallery","listname":"galleries","type":"gallery"}]}}
Now my first attempt was to parse this link the way I parse homepages:
guard let myURL = URL(string: link) else { > print("Error: \(link) doesn't seem to be a valid URL")
return
}
do {
link = try String(contentsOf: myURL, encoding: .ascii)
} catch let error {
print("Error: \(error)")
}
But this doesn't work as I now understand that's because this is JSON coded?!
I searched for parsing JSON and found some explanations for encoding and decoding, but my problem is that in all examples given, the explanations start by "having" already the contents of the JsonObject.
My problem is that I can read the contents of the URL in the browser but I would need the content of the URL in Xcode itself, so I can parse it?!
So in my specific case I would only need the content of "imageurl_lg"
...I would know how to do it if I could display the content I can see in my browser also in Xcode - but how do I get the contents of the link into Xcode?
For reference, I also read following instructions, but couldn't apply them to my example...
https://www.raywenderlich.com/172145/encoding-decoding-and-serialization-in-swift-4
https://grokswift.com/json-swift-4/
and some more but they didn't help me...
You need to use a URLSession task to do this, and after that you need to use JSONSerialization in this example I return a dictionary of [String:Any] you can convert it to whatever Model you need
Use this Code
func fetchData(completion: #escaping ([String:Any]?, Error?) -> Void) {
let url = URL(string: "http://api.geekdo.com/api/images?ajax=1&gallery=all&nosession=1&objectid=127023&objecttype=thing&pageid=357&showcount=1&size=thumb&sort=recent")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data else { return }
do {
if let array = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String:Any]{
completion(array, nil)
}
} catch {
print(error)
completion(nil, error)
}
}
task.resume()
}
How use it
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
fetchData { (dict, error) in
debugPrint(dict)
}
}
Result Log printed
Optional(["config": {
categories = (
{
name = All;
type = "";
},
{
name = BoxFront;
type = BoxFront;
},
{
name = BoxBack;
type = BoxBack;
},
{
name = Components;
type = Components;
},
{
name = Customized;
type = Customized;
},
{
name = Play;
type = Play;
},
{
name = Miscellaneous;
type = Miscellaneous;
},
{
name = Mature;
type = Mature;
},
{
name = Uncategorized;
type = uncat;
}
);
datefilters = (
{
name = "All Time";
value = alltime;
},
{
name = Today;
value = today;
},
{
name = "Two Days";
value = twodays;
},
{
name = "Last 7 Days";
value = last7;
},
{
name = "Last 30 Days";
value = last30;
},
{
name = "Last 365 Days";
value = year;
}
);
endpage = 402;
filters = (
{
listname = licensefilters;
name = Licenses;
type = licensefilter;
},
{
listname = categories;
name = Category;
type = tag;
},
{
listname = galleries;
name = Gallery;
type = gallery;
}
);
galleries = (
{
name = All;
type = all;
},
{
name = Game;
type = game;
},
{
name = People;
type = people;
},
{
name = Creative;
type = creative;
}
);
licensefilters = (
{
name = Any;
type = "";
},
{
name = "Copying allowed";
type = reuse;
},
{
name = "Commercial use allowed";
type = commercial;
},
{
name = "Modification allowed";
type = modify;
}
);
numitems = 402;
sorttypes = (
{
name = Hot;
type = hot;
},
{
name = Recent;
type = recent;
}
); }, "images": <__NSSingleObjectArrayI 0x600000010710>( {
caption = "White power tiles";
imageid = 1567153;
imageurl = "https://cf.geekdo-images.com/6fCr14v025ZKYhXRMnbhYR16Ta8=/fit-in/200x150/pic1567153.jpg";
"imageurl_lg" = "https://cf.geekdo-images.com/images/pic1567153_lg.jpg";
name = "<null>";
numcomments = 0;
numrecommend = 6;
user = {
avatar = 1;
avatarfile = "avatar_id33829.jpg";
username = manosdowns;
}; } ) ])
Updated fixing "App Transport Security has blocked a cleartext" error
Adjust your info.plist
So this is what playground gave me.
import UIKit
var str = "Hello, playground"
func makeGetCall() {
guard let myURL = URL(string: "http://api.geekdo.com/api/images?ajax=1&gallery=all&nosession=1&objectid=127023&objecttype=thing&pageid=357&showcount=1&size=thumb&sort=recent") else {
print("Error: \(link) doesn't seem to be a valid URL")
return
}
do {
var content = try String(contentsOf: myURL, encoding: .ascii)
print("Content: \(content)")
} catch let error {
print("Error: \(error)")
}
}
makeGetCall()
Prints

Parsing JSON using a Swift Dictionary

I am having a hard time parsing JSON with Swift. I have written a function that make a get request to an api and retrieves the data as JSON and converts it into a dictionary. After that I am trying to use a tableViewController to set each title and subtitle from the values I received from the JSON. I am trying to set the title as the homeTeam and the subtitle as the awayTeam. I do not know much about Swift so I was hoping for some help.
Here is my JSON that is stored in a dictionary:
dictionary = ["scoreboard": {
gameScore = (
{
game = {
ID = 35119;
awayTeam = {
Abbreviation = ATL;
City = Atlanta;
ID = 91;
Name = Hawks;
};
date = "2017-04-07";
homeTeam = {
Abbreviation = CLE;
City = Cleveland;
ID = 86;
Name = Cavaliers;
};
location = "Quicken Loans Arena";
time = "7:30PM";
};
isCompleted = false;
isInProgress = false;
isUnplayed = true;
quarterSummary = "<null>";
},
{
game = {
ID = 35120;
awayTeam = {
Abbreviation = MIA;
City = Miami;
ID = 92;
Name = Heat;
};
date = "2017-04-07";
homeTeam = {
Abbreviation = TOR;
City = Toronto;
ID = 81;
Name = Raptors;
};
location = "Air Canada Centre";
time = "7:30PM";
};
isCompleted = false;
isInProgress = false;
isUnplayed = true;
quarterSummary = "<null>";
},
{
game = {
ID = 35121;
awayTeam = {
Abbreviation = NYK;
City = "New York";
ID = 83;
Name = Knicks;
};
date = "2017-04-07";
homeTeam = {
Abbreviation = MEM;
City = Memphis;
ID = 107;
Name = Grizzlies;
};
location = "FedEx Forum";
time = "8:00PM";
};
isCompleted = false;
isInProgress = false;
isUnplayed = true;
quarterSummary = "<null>";
},
{
game = {
ID = 35122;
awayTeam = {
Abbreviation = DET;
City = Detroit;
ID = 88;
Name = Pistons;
};
date = "2017-04-07";
homeTeam = {
Abbreviation = HOU;
City = Houston;
ID = 109;
Name = Rockets;
};
location = "Toyota Center";
time = "8:00PM";
};
isCompleted = false;
isInProgress = false;
isUnplayed = true;
quarterSummary = "<null>";
},
{
game = {
ID = 35123;
awayTeam = {
Abbreviation = SAS;
City = "San Antonio";
ID = 106;
Name = Spurs;
};
date = "2017-04-07";
homeTeam = {
Abbreviation = DAL;
City = Dallas;
ID = 108;
Name = Mavericks;
};
location = "American Airlines Center";
time = "8:30PM";
};
isCompleted = false;
isInProgress = false;
isUnplayed = true;
quarterSummary = "<null>";
},
{
game = {
ID = 35124;
awayTeam = {
Abbreviation = NOP;
City = "New Orleans";
ID = 110;
Name = Pelicans;
};
date = "2017-04-07";
homeTeam = {
Abbreviation = DEN;
City = Denver;
ID = 99;
Name = Nuggets;
};
location = "Pepsi Center";
time = "9:00PM";
};
isCompleted = false;
isInProgress = false;
isUnplayed = true;
quarterSummary = "<null>";
},
{
game = {
ID = 35125;
awayTeam = {
Abbreviation = MIN;
City = Minnesota;
ID = 100;
Name = Timberwolves;
};
date = "2017-04-07";
homeTeam = {
Abbreviation = UTA;
City = Utah;
ID = 98;
Name = Jazz;
};
location = "Vivint Smart Home Arena";
time = "9:00PM";
};
isCompleted = false;
isInProgress = false;
isUnplayed = true;
quarterSummary = "<null>";
},
{
game = {
ID = 35126;
awayTeam = {
Abbreviation = OKL;
City = "Oklahoma City";
ID = 96;
Name = Thunder;
};
date = "2017-04-07";
homeTeam = {
Abbreviation = PHX;
City = Phoenix;
ID = 104;
Name = Suns;
};
location = "Talking Stick Resort Arena";
time = "10:00PM";
};
isCompleted = false;
isInProgress = false;
isUnplayed = true;
quarterSummary = "<null>";
},
{
game = {
ID = 35127;
awayTeam = {
Abbreviation = SAC;
City = Sacramento;
ID = 103;
Name = Kings;
};
date = "2017-04-07";
homeTeam = {
Abbreviation = LAL;
City = "Los Angeles";
ID = 105;
Name = Lakers;
};
location = "Staples Center";
time = "10:30PM";
};
isCompleted = false;
isInProgress = false;
isUnplayed = true;
quarterSummary = "<null>";
}
);
lastUpdatedOn = "<null>";
}]
Here is what I have currently for setting my title and subtitle in Swift:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "NBAScore", for: indexPath)
// Configure the cell...
if let scoreBoard = d.dictionary["scoreboard"] as? [String:AnyObject]
{
if let gameScore = scoreBoard["gameScore"] as? [String:AnyObject]
{
if let game = gameScore["game"] as? [String:AnyObject]
{
if let awayTeam = game["awayTeam"] as? String
{
cell.textLabel?.text = awayTeam }
}
}
}
return cell
}
Best will be to create a Struct add variable's for the properties you need after that make an array from that struct parse your array of json using a for loop and append them to the newly array you have created then you can access those properties using dot notation inside your cellForRow function
Use the below code to get the team name -
if let scoreBoard = d.dictionary["scoreboard"] as? [String:AnyObject]
{
if let gameScore = scoreBoard["gameScore"] as? [String:AnyObject]
{
if let game = gameScore["game"] as? [String:AnyObject]
{
if let awayTeam = game["awayTeam"] as? [String: AnyObject] {
if let teamName = awayTeam["Name"] as? String {
cell.textLabel?.text = teamName
}
}
}
}
}
For that purpose I would use some library that was build to parse JSON dictionaries to some model objects as it's a good practice. E.g. I would recommend Marshal as it's lightweight and easy to use.
You just create a struct or any other Swift structure and then you call Marshal. Later on you use those mapped objects in your tableView dataSource.
Your 'gameScore' object is an array not a dictionary type ([String:AnyObject]). My mistake that i didn't check the json object properly.
First create an array and store all the team name in that array. For Example, I am storing all the awayteam name for now in an array. Check the below code. I didn't run the below source code in my end, Since your json has problem. It's not a valid json data. There is formatting issue. But this below code will work.
let awayTeamArr = NSMutableArray()
if let scoreBoard = d.dictionary["scoreboard"] as? [String:AnyObject] {
if let gameScore = scoreBoard["gameScore"] as? NSArray {
for gameScoreObj in gameScore {
if let gameObj = gameScoreObj as [String: AnyObject] {
if let game = gameObj["game"] as? [String:AnyObject] {
if let awayTeam = game["awayTeam"] as? [String: AnyObject] {
if let teamName = awayTeam["Name"] as? String {
awayTeam.add(teamName)
}
}
}
}
}
}
}
Then in your tableView delegate method for each cell display the object of that specific index of 'awayTeamArr' object. If this answer worked then make the question as completed.
I was able to figure out an answer to my own question. The "gameScore" key of the dictionary was giving me trouble because I was type casting it incorrectly. It was an Array<[String:Any]> not a dictionary.
func parseJSON(){
var s = nbaScore()
var i = 0
if let scoreBoard = d.dictionary["scoreboard"] as? [String:AnyObject]
{
// Could check the lastUpdattedOn date before doing the following:
if let gameScore = scoreBoard["gameScore"] as? Array<[String:Any]>
{ //Loop for # of games
//while gameScore[i]["game"] as? [String:Any] != nil
while i < gameScore.count
//for _ in (gameScore[0]["game"] as? [String:Any])!
{
// An array of dictionaries
if let game = gameScore[i]["game"] as? [String:Any]
{
s.gameTime = (game["time"] as? String)!
if let awayTeam = game["awayTeam"] as? [String:Any]
{
s.awayTeamCity = (awayTeam["City"] as? String)!
s.awayTeamName = (awayTeam["Name"] as? String)!
}
if let homeTeam = game["homeTeam"] as? [String:Any]
{
s.homeTeamCity = (homeTeam["City"] as? String)!
s.homeTeamName = (homeTeam["Name"] as? String)!
}
}
if let isUnplayed = gameScore[i]["isUnplayed"] as? String
{
s.isUnplayed = isUnplayed
}
if let isInProgress = gameScore[i]["isInProgress"] as? String
{
s.isInProgress = isInProgress
}
if let isCompleted = gameScore[i]["isCompleted"] as? String
{
s.isCompleted = isCompleted
}
if let awayScore = gameScore[i]["awayScore"] as? String
{
s.awayTeamScore = awayScore
}
if let homeScore = gameScore[i]["homeScore"] as? String
{
s.homeTeamScore = homeScore
}
i += 1
scores.append(s)
s.clearData()
gamesCount += 1
}
}
}
}

My all data are not getting stored in Coredata

I'm fetching values from Server and storing them to Coredata.The issue is coming that when i fetch data from server and store them in coredata, it shows that i have stored my values all values.....
These are my data which are been stored:
[{
adName = Britannia;
adType = Video;
addescription = "Choco Muffills come with thick chocolate filling that will take you by surprise.";
clientImage = "http://api.weoneapp.com:8595/1464528609370.png";
clientName = Britannia;
endDate = "Just now";
entryId = 1478230186228;
likeFlag = 0;
mainImage = "";
newAdvertisement = 1;
noOfCount = 1367;
noOfLike = 2783;
seenAdvertisement = 0;
smilURL = "http://52.66.101.222:1935/vod/_definst_/1478230186228/smil:1478230186228.smil/playlist.m3u8";
sortDate = "2016-11-03T19:27:00.000Z";
startDate = "2016-11-03T19:27:00.000Z";
subTitle = "Britannia Cake Muffills";
thumbNail = "http://52.66.101.222:8595/video/1478230186228/1478230186228_thumbnail.png";
videoDownloadUrl = "http://52.66.101.222:8595/video/1478230186228/1478230186228_source.mp4";
}, {
adName = "Kwality Walls";
adType = Video;
addescription = "Paddle Pop Yummy Delicious Dessert - A delicious, colourful and yummy dessert ... Walls India \U00b7 Kulfeez from Kwality Walls India \U00b7";
clientImage = "http://api.weoneapp.com:8595/1464524885184.jpg";
clientName = "Kwality Walls";
endDate = "Just now";
entryId = 1478230623594;
likeFlag = 0;
mainImage = "";
newAdvertisement = 1;
noOfCount = 1281;
noOfLike = 2618;
seenAdvertisement = 0;
smilURL = "http://52.66.101.222:1935/vod/_definst_/1478230623594/smil:1478230623594.smil/playlist.m3u8";
sortDate = "2016-11-03T18:36:00.000Z";
startDate = "2016-11-03T18:36:00.000Z";
subTitle = "Paddle Pop Jiggly Jelly";
thumbNail = "http://52.66.101.222:8595/video/1478230623594/1478230623594_thumbnail.png";
videoDownloadUrl = "http://52.66.101.222:8595/video/1478230623594/1478230623594_source.mp4";
}, {
adName = "Cadbury Dairy Milk";
adType = Video;
addescription = "Your favourite chocolate is now more chocolatey.";
clientImage = "http://api.weoneapp.com:8595/1464017173884.jpg";
clientName = Cadbury;
endDate = "Just now";
entryId = 1478230473291;
likeFlag = 0;
mainImage = "";
newAdvertisement = 0;
noOfCount = 1310;
noOfLike = 2600;
seenAdvertisement = 1;
smilURL = "http://52.66.101.222:1935/vod/_definst_/1478230473291/smil:1478230473291.smil/playlist.m3u8";
sortDate = "2016-11-03T18:32:00.000Z";
startDate = "2016-11-03T18:32:00.000Z";
subTitle = "Cadbury Dairy Milk";
thumbNail = "http://52.66.101.222:8595/video/1478230473291/1478230473291_thumbnail.png";
videoDownloadUrl = "http://52.66.101.222:8595/video/1478230473291/1478230473291_source.mp4";
}]
Now when i go to my .sqlite folder, which is at this location : /Users/Johnn/Library/Developer/CoreSimulator/Devices/0DF66BFE-6076-45E9-8325-D61F1C738DFA/data/Containers/Data/Application/DC3F7B17-1172-4AE3-BC3B-217624C21AA5/Documents/AppCoreData.sqlite
and open this .sqlite file> Go to my table i found:
that only two values are stored my last value of entry is empty.
I don't know what's the reason behind this,why my last value of array is not getting stored in database...
I am storing the values like this:
class func createInManagedObjectContext(nameOfAdvert: String, thumbnail: String, fileName: String, videoDownloadUrl: String, subTitle: String, adType: String, mainImage: String, noOfLike: NSNumber, entryId: String, likeFlag: Bool, startDate: String, endDate: String, noOfCount: NSNumber ,clientName: String, clientImage: String, adDesc: String, sortDate: String, newAdvertisement: Bool, seenAdvertisement: Bool) -> Tube {
let managedObjectContext = DataAccess.shared.managedObjectContext
let newItems = NSEntityDescription.insertNewObjectForEntityForName("Tube", inManagedObjectContext: managedObjectContext) as! Tube
do {
try managedObjectContext.save()
newItems.adName = nameOfAdvert
newItems.thumbNail = thumbnail
newItems.smilURL = fileName
newItems.videoDownloadUrl = videoDownloadUrl
newItems.subTitle = subTitle
newItems.adType = adType
newItems.mainImage = mainImage
newItems.noOfLike = noOfLike
newItems.entryId = entryId
newItems.likeFlag = likeFlag
newItems.startDate = startDate
newItems.endDate = endDate
newItems.noOfCount = noOfCount
newItems.clientImage = clientImage
newItems.clientName = clientName
newItems.addescription = adDesc
newItems.sortDate = sortDate
newItems.newAdvertisement = newAdvertisement
newItems.seenAdvertisement = seenAdvertisement
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
print("-----------------------------")
print(newItems)
return newItems
}
I am not knowing why all data are not getting saved in the coredata. Any help will be appreciated.
Thanks in advance
Please write this code :->
Write try managedObjectContext.save() after you insert data.
class func createInManagedObjectContext(nameOfAdvert: String, thumbnail: String, fileName: String, videoDownloadUrl: String, subTitle: String, adType: String, mainImage: String, noOfLike: NSNumber, entryId: String, likeFlag: Bool, startDate: String, endDate: String, noOfCount: NSNumber ,clientName: String, clientImage: String, adDesc: String, sortDate: String, newAdvertisement: Bool, seenAdvertisement: Bool) -> Tube {
let managedObjectContext = DataAccess.shared.managedObjectContext
let newItems = NSEntityDescription.insertNewObjectForEntityForName("Tube", inManagedObjectContext: managedObjectContext) as! Tube
newItems.adName = nameOfAdvert
newItems.thumbNail = thumbnail
newItems.smilURL = fileName
newItems.videoDownloadUrl = videoDownloadUrl
newItems.subTitle = subTitle
newItems.adType = adType
newItems.mainImage = mainImage
newItems.noOfLike = noOfLike
newItems.entryId = entryId
newItems.likeFlag = likeFlag
newItems.startDate = startDate
newItems.endDate = endDate
newItems.noOfCount = noOfCount
newItems.clientImage = clientImage
newItems.clientName = clientName
newItems.addescription = adDesc
newItems.sortDate = sortDate
newItems.newAdvertisement = newAdvertisement
newItems.seenAdvertisement = seenAdvertisement
do {
try managedObjectContext.save()
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
print("-----------------------------")
print(newItems)
return newItems
}

AutoCompleteTextField and Firebase

I am trying to integrate Firebase and AutoCompleteTextField in Swift so that I have autocomplete in the textField. I'm having a problem trying to turn the dictionary into an array so that I can set it in autoCompleteTextField.autoCompleteStrings. This is the code I have for it.
func handleTextFieldInterfaces() {
let ref = FIRDatabase.database().reference().child("Airport")
ref.observeEventType(.Value, withBlock: { (snapshot) in
self.autoCompleteTextField.onTextChange = {[weak self] text in
if !text.isEmpty {
var fbosStuff = [String]()
if let snaps = snapshot.value as? [[String: AnyObject]] {
for places in snaps {
print(places)
let names = places["code"] as? String
fbosStuff.append(names!)
}
self!.autoCompleteTextField.autoCompleteStrings = fbosStuff
}
}
}
})
}
and the response from Firebase that I am trying to put into the textfield is.
Snap (Airport) {
"Long Beach" = {
FBOs = {
Atlantic = {
100LL = "7.0";
freq = "120.1";
fullname = "Atlantic, Long Beach, KLGB";
"jet-A" = "5.5";
"phone number" = "(800) 554-3591";
};
Signature = {
100ll = "7.0";
email = "lgb#signatureflight.com";
freq = "120.1";
fullname = "Signature, Long Beach, KLGB";
"jet-a" = "5.5";
phonenumber = "(800) 554-3591";
};
};
code = KLGB;
fieldname = Daughtery;
location = "Long Beach, California, USA";
};
"Santa Monica" = {
FBOs = {
"American Flyers" = {
100ll = "5.38";
freq = "123.3";
fullname = "American Flyers, Santa Monica, KSMO";
phonenumber = "(310) 390-2099";
};
Atlantic = {
100ll = "7.79";
freq = "122.95";
fullname = "Atlantic, Santa Monica, KSMO";
"jet-a" = "7.19";
phonenumber = "(310) 396-6770";
};
};
code = KSMO;
fieldname = "Santa Monica Muni Airport";
location = "Santa Monica, California, USA";
};
}
Try :-
Swift 2
for places in snaps {
print(places.0) // Will give you the key
let names = places["code"] as? String
fbosStuff.append(names!)
}
Swift 3
for places in snaps {
print(places.key) // Will give you the key
let names = places["code"] as? String
fbosStuff.append(names!)
}

NIL when Parsing JSON

I am trying to parse and get the values from this structure of JSON:
["mst_customer": 1, "data": {
0 = 2;
1 = 1;
2 = 1;
3 = "JAYSON TAMAYO";
4 = "581-113-113";
5 = 56;
6 = on;
7 = g;
8 = jayson;
9 = active;
"app_access" = on;
id = 2;
"mst_customer" = 1;
name = "Jayson Tamayo";
status = active;
territory = 1;
}, "status": OK, "staff_id": 2, "staff_name": Jayson Tamayo]
I use the following Swift code to get the values:
(data: Dictionary<String, AnyObject>, error: String?) -> Void in
if error != nil {
print(error)
} else {
if let feed = data["data"] as? NSDictionary ,let entries = data["data"] as? NSArray{
for elem: AnyObject in entries{
if let staff_name = elem["name"] as? String{
print(staff_name)
}
}
}
}
I am trying to get the name by using the keys name or staff_name. But I always get nil.
you want to access staff_name, which is not in "data" variable ... you can simply get that like
if error != nil {
print(error)
} else {
if let name = data["staff_name"] as? String{
print(name)
}
}
for elem: AnyObject in entries{
if let songName = elem["name"] as? String{
print(songName)
}
}
//replace above code with below code
if let songName : String = entries["name"] as? String{
print(songName)
}

Resources