Reading JSON file with Swift 3 - ios

With this code i can show the "result"
var movies: [NSDictionary]?
var dates: NSDictionary?
func fetchNowPlayingMovies(){
let apiKey = "8e3967947a95555f9c430e68d070a0e7"
let url = URL(string: "https://api.themoviedb.org/3/movie/now_playing?api_key=\(apiKey)"+"&language=en-US&page=1")
let request = URLRequest(url: url! as URL, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 10)
let session = URLSession(configuration: URLSessionConfiguration.default, delegate: nil, delegateQueue: OperationQueue.main)
let task: URLSessionDataTask = session.dataTask(with:request, completionHandler: {(dataOrNil, reponse, error) in
if let data = dataOrNil{
if let responseDictionary = try! JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary {
//print("reponse: \(responseDictionary)")
self.movies = responseDictionary["results"] as? [NSDictionary]
self.dates = responseDictionary["dates"] as? NSDictionary
self.tableView.reloadData()
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
})
task.resume()
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MovieCell", for: indexPath) as! MovieTableViewCell
//MARK: - JSON Properties
let movie = movies![indexPath.row]
let date = dates![indexPath.row]
let title = movie["title"] as! String
let vote_average = movie["vote_average"] as! Double
let overview = movie["overview"] as! String
let baseUrl = "http://image.tmdb.org/t/p/w500"
let posterPath = movie["poster_path"] as! String
let imageUrl = URL(string: baseUrl + posterPath)
// Configure the cell...
cell.lblTitle.text = title
cell.lblOverview.text = overview
cell.lblVoteAVG.text = String(vote_average)
cell.imgPosterPath.sd_setImage(with: imageUrl)
return cell
}
Request: https://api.themoviedb.org/3/movie/now_playing?api_key=8e3967947a95555f9c430e68d070a0e7&language=en-US&page=1
How i can get the "page" and the "maximum" in "dates"?
Thank you!

var movies: [NSDictionary]?
var dates: NSDictionary?
var page: Int? // var for page
var maximum: String? // var for maximum in dates
func fetchNowPlayingMovies(){
let apiKey = "8e3967947a95555f9c430e68d070a0e7"
let url = URL(string: "https://api.themoviedb.org/3/movie/now_playing?api_key=\(apiKey)"+"&language=en-US&page=1")
let request = URLRequest(url: url! as URL, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 10)
let session = URLSession(configuration: URLSessionConfiguration.default, delegate: nil, delegateQueue: OperationQueue.main)
let task: URLSessionDataTask = session.dataTask(with:request, completionHandler: {(dataOrNil, reponse, error) in
if let data = dataOrNil{
if let responseDictionary = try! JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary {
//print("reponse: \(responseDictionary)")
self.movies = responseDictionary["results"] as? [NSDictionary]
self.dates = responseDictionary["dates"] as? NSDictionary
// This is how you get to page
print("page: \(responseDictionary["page"]!)")
self.page = responseDictionary["page"] as? Int
print("page: \(self.page!)")
// This is how you get to maximum in dates
self.maximum = self.dates?["maximum"] as? String
print("maximum: \(self.maximum!)")
self.tableView.reloadData()
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
})
task.resume()
}
I hope it helped

Related

Duplicate array items getting appended in Response (Swift)

I am using two APIs, one for fetching the Cars added by the user and the second to (Adding new car) submit the car details into my backend. When I open the View of the car details, all 11 Car details are getting fetched properly.
But when I submit the car details (Add New Car) by clicking the add rounded button and the fetch the details of the added car it shows 22 car added in the frontend Table View but now in the backend of the API.
Here are some screenshots.
Before adding a new car
After adding a new car
Here is the code for the same.
Below function is getting used in Viewdidload to fetch the details:
func responsedatavehicle(){
let emailid = defaults.string(forKey: "email")
var request = URLRequest(url: URL(string: "http://www.example.com/getMyVehicleInfo?email=\(emailid!)")!)
print("Email in resposfunction \(emailid!)")
request.httpMethod = "GET"
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
do{
// let postString = "?mobile="+ph!
print("mobno is inside getdata \(emailid!)")
// //print(postString)
// request.httpBody = postString.data(using: .utf8)
APESuperHUD.show(style: .loadingIndicator(type: .standard), title: nil, message: "Loading...")
//self.activityIndicator("Please Wait")
}catch let error{
//print(error.localizedDescription)
return
}
// self.activityIndicator("Please Wait")
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if error != nil
{
return
}
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
do{
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json{
print(parseJSON)
if let mobile = parseJSON["error"] as! Int? {
let msg = parseJSON["message"] as! String?
if (mobile == 0){
//print(userId)
DispatchQueue.main.async {
// self.showGlobalAlertwithMessage(msg as! NSString)
if let heroeArray = json!.value(forKey: "content") as? Array<[String:Any]> {
//looping through all the elements
self.labelArray.append(contentsOf: heroeArray)
}
APESuperHUD.dismissAll(animated: true)
// self.effectView.removeFromSuperview()
//print(self.labelArray.count)
for i in 0..<self.labelArray.count{
if let heroeDict = self.labelArray[i] as? NSDictionary{
// let stationname = heroeDict.value(forKey: "charging_station") as! String
let brandname = heroeDict.value(forKey: "brand_name") as! String
let modelname = heroeDict.value(forKey: "car_name") as! String
let accharger = heroeDict.value(forKey: "ac_charger") as! String
let dccharger = heroeDict.value(forKey: "dc_charger") as! String
let vehiclenumber = heroeDict.value(forKey: "vehicle_registration_number") as! String
let imageurl = heroeDict.value(forKey: "vehicle_photo") as! String
self.brandnamearray.append(brandname)
self.modelnamearray.append(modelname)
self.acchargerarray.append(accharger)
self.dcchargerarray.append(dccharger)
self.imageurlarray.append(imageurl)
self.vehiclenoarray.append(vehiclenumber)
print(self.imageurlarray)
}
}
self.myTableView.reloadWithAnimation()
}
}else {
DispatchQueue.main.async {
//self.showGlobalAlertwithMessage(msg as! NSString)
DispatchQueue.main.async {
APESuperHUD.dismissAll(animated: true)
// self.effectView.removeFromSuperview()
}
}
}
}
} else{
print("ERROR IN ALERT")
}
}
catch{
// self.showGlobalAlertwithMessage("Could not successfully perform this request. Please try again later")
}
}
task.resume()
}
Cellforrowat Function
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MyVehicleTableViewCell
cell.brandnamecell.text = brandnamearray[indexPath.row]
cell.modelnamecell.text = modelnamearray[indexPath.row]
cell.acchargercell.text = acchargerarray[indexPath.row]
cell.dcchargercell.text = dcchargerarray[indexPath.row]
cell.vehiclenumbercell.text = vehiclenoarray[indexPath.row]
cell.ImageView.sd_setImage(with: URL(string: imageurlarray[indexPath.row]), placeholderImage: UIImage(named: "placeholder.png"))
cell.aclabel.layer.borderColor = UIColor.darkGray.cgColor
cell.aclabel.layer.borderWidth = 1.0
cell.aclabel.layer.cornerRadius = 5
cell.aclabel.layer.masksToBounds = true
cell.dclabel.layer.borderColor = UIColor.darkGray.cgColor
cell.dclabel.layer.cornerRadius = 5
cell.dclabel.layer.masksToBounds = true
cell.dclabel.layer.borderWidth = 1.0
cell.aclabel.layer.shadowColor = UIColor.lightGray.cgColor
cell.aclabel.layer.shadowOpacity = 0.5
cell.aclabel.layer.shadowRadius = 10.0
cell.aclabel.layer.shadowOffset = .zero
cell.aclabel.layer.shadowPath = UIBezierPath(rect: cell.aclabel.bounds).cgPath
cell.aclabel.layer.shouldRasterize = true
cell.dclabel.layer.shadowColor = UIColor.lightGray.cgColor
cell.dclabel.layer.shadowOpacity = 0.5
cell.dclabel.layer.shadowRadius = 10.0
cell.dclabel.layer.shadowOffset = .zero
cell.dclabel.layer.shadowPath = UIBezierPath(rect: cell.dclabel.bounds).cgPath
cell.dclabel.layer.shouldRasterize = true
cell.backview.layer.borderColor = UIColor(red:0.92, green:0.92, blue:0.98, alpha:0.9).cgColor
cell.backview.layer.cornerRadius = 8
cell.backview.layer.masksToBounds = true
cell.backview.layer.borderWidth = 8.0
cell.shadowmodel.layer.cornerRadius = 13.0
cell.shadowmodel.layer.shadowColor = UIColor.lightGray.cgColor
cell.shadowmodel.layer.shadowOpacity = 0.5
cell.shadowmodel.layer.shadowRadius = 10.0
cell.shadowmodel.layer.shadowOffset = .zero
cell.shadowmodel.layer.shadowPath = UIBezierPath(rect: cell.shadowmodel.bounds).cgPath
cell.shadowmodel.layer.shouldRasterize = true
return cell
}
Below function is getting used to add a new car:
func submitcar(){
if vehiclenumberstring == ""{
SCLAlertView().showError("Error", subTitle: "Please enter vehicle number ") // Error
}
else {
let emailsubmit = defaults.string(forKey: "email")
print("email inside submit car is \(emailsubmit!)")
var request = URLRequest(url: URL(string: "http://www.example.com/apimobileapps/addVehicleInfo")!)
request.httpMethod = "POST"
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
do{
let postString = "brand_name="+brandname+"&car_name="+modelname+"&vehicle_registration_number="+vehiclenumberstring+"&email="+emailsubmit!
print(postString)
request.httpBody = postString.data(using: .utf8)
APESuperHUD.show(style: .loadingIndicator(type: .standard), title: nil, message: "Loading...")
// self.activityIndicator("Please Wait")
}catch let error{
//print(error.localizedDescription)
return
}
let task = URLSession.shared.dataTask(with: request){
(data, response, error) in
if (error != nil){
return
}
do{
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json{
//print(parseJSON)
if let userId = parseJSON["error"] as! Int? {
let msg = parseJSON["message"] as! String?
if (userId == 0){
//print(userId)
DispatchQueue.main.async {
// self.showGlobalAlertwithMessage(msg as! NSString)
DispatchQueue.main.async {
APESuperHUD.dismissAll(animated: true); self.effectView.removeFromSuperview()
}
}
}else {
DispatchQueue.main.async {
// self.showGlobalAlertwithMessage(msg as! NSString)
DispatchQueue.main.async {
APESuperHUD.dismissAll(animated: true)
// self.effectView.removeFromSuperview();
}
}
}
}
} else{
DispatchQueue.main.async {
APESuperHUD.dismissAll(animated: true)
// self.effectView.removeFromSuperview();
}
}
}catch{
DispatchQueue.main.async {
APESuperHUD.dismissAll(animated: true)
// self.effectView.removeFromSuperview();
}
//print(error)
}
}
task.resume()
}
responsedatavehicle()
}
My Array count is showing duplicate values in the table view on submit button action.

Data Out of Order

I am using the Flickr API to get all albums within a collection and then using the album IDs from to get the primary photo for each of the albums. It works but the photos are not returned to me in order so the primary photo for each album does not match up to the album titles in my collection view.
func getPhotoCollection() {
let collectionURLString = "https://api.flickr.com/services/rest/?method=flickr.collections.getTree&api_key={API_KEY}&collection_id=72157676119666248&user_id={USER_ID}&format=json&nojsoncallback=1"
self.session = URLSession(configuration: .default, delegate: self, delegateQueue: nil)
let task = self.session?.dataTask(with: URL(string: collectionURLString)!, completionHandler: { (data, response, error) in
let json = self.getJSONFrom(urlString: collectionURLString)
let collections = json["collections"]
let collection = collections["collection"].arrayObject as! [[String:AnyObject]]
for collectionObject in collection {
let sets = collectionObject["set"] as! [[String: AnyObject]]
for set in sets {
let albumId = set["id"] as! String
let albumTitle = set["title"] as! String
self.albumIds.append(albumId)
self.albumTitles.append(albumTitle)
}
}
self.getAlbumPrimary()
})
task?.resume()
}
func getAlbumPrimary() {
for albumId in self.albumIds {
let apiURLString = "https://api.flickr.com/services/rest/?method=flickr.photosets.getPhotos&api_key={API_KEY}&photoset_id=\(albumId)&per_page=1&user_id={USER_ID}&format=json&nojsoncallback=1"
self.session = URLSession(configuration: .default, delegate: self, delegateQueue: nil)
let task = self.session?.dataTask(with: URL(string: apiURLString)!, completionHandler: { (data, response, error) in
let json = self.getJSONFrom(urlString: apiURLString)
let photos = json["photoset"]
let photo = photos["photo"].arrayObject as! [[String:AnyObject]]
let primaryPic = photo[0]
let farm = primaryPic["farm"] as! Int
let server = primaryPic["server"] as! String
let picId = primaryPic["id"] as! String
let secret = primaryPic["secret"] as! String
let urlString = String(format: "https://farm%d.static.flickr.com/%#/%#_%#_b.jpg", farm, server, picId, secret)
self.albumPrimaryURLs.append(urlString)
DispatchQueue.main.async {
self.collectionView.reloadData()
self.loaded = true
}
})
task?.resume()
}
}
This is the way multiple asynchronous tasks work ( out of order ) ,you need to create a model instead of seperate arrays then load from the data to fill the last property
class Item {
let id,title:String
var url:String?
init(id:String,title:String){
self.id = id
self.title = title
}
func loadUrl(completion:#escaping () -> () ) {
// here load and set the url
}
}
var items = [Item]() // declare main array
let albumId = set["id"] as! String
let albumTitle = set["title"] as! String
let item = Item(id:albumId,title:albumTitle)
self.items.append(item)
Then to load the collection finally
let g = DispatchGroup()
items.forEach {
g.enter()
$0.loadUrl {
g.leave()
}
}
g.notify(queue:.main) {
self.collectionView.reloadData()
self.loaded = true
}

Cannot convert value of type string to type url in coercion

I'm receiving the error Cannot convert value of type string
to type url in coercion at this constant. Thanks for the help ahead of time :)
**let safariVC = SFSafariViewController(url: JobUrl as URL)**
import UIKit
import SafariServices
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
//Indeed API Query as JSON
final let urlString = "http://api.indeed.com/ads/apisearch?publisher=9727336427429597&as_phr=&as_any=&as_not=&as_ttl=&as_cmp=&jt=parttime&st=&salary=&radius=25&l=32304&fromage=any&limit=25&sort=&psf=advsrch=&userip=1.2.3.4&useragent=Mozilla/%2F4.0%28Firefox%29&v=2&format=json"
#IBOutlet weak var tableView: UITableView!
var jobTitleArray = [String]()
var snippetArray = [String]()
var companyArray = [String]()
var cityArray = [String]()
var jobUrlArray = [String]()
// url = URL(string: epsDictionary["link"] as! String)
override func viewDidLoad() {
super.viewDidLoad()
self.downloadJsonWithURL()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
//dispose of any resources that can be recreated
}
//fetch Json
func downloadJsonWithURL() {
let url = NSURL(string: urlString)
URLSession.shared.dataTask(with: (url as? URL)!, completionHandler: {(data, response, error) ->
Void in
if let JsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)
as? NSDictionary {
print(JsonObj!.value(forKey: "results")!)
if let resultsArray = JsonObj!.value(forKey: "results") as? NSArray {
for result in resultsArray {
if let resultDict = result as? NSDictionary {
if let jobTitle = resultDict.value(forKey: "jobtitle") {
self.jobTitleArray.append(jobTitle as! String)
}
if let snippet = resultDict.value(forKey: "snippet") {
self.snippetArray.append(snippet as! String)
}
if let company = resultDict.value(forKey: "company") {
self.companyArray.append(company as! String)
}
if let city = resultDict.value(forKey: "formattedRelativeTime") {
self.cityArray.append(city as! String)
}
if let jobUrl1 = resultDict.value(forKey: "url") {
self.jobUrlArray.append(jobUrl1 as! String)
}
OperationQueue.main.addOperation({
self.tableView.reloadData()
})
}
}
}
}
}).resume()
}
func downloadJsonWithTask() {
let url = NSURL(string: urlString)
var downloadTask = URLRequest(url: (url as? URL)!, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 20)
downloadTask.httpMethod = "Get"
URLSession.shared.dataTask(with: (url as? URL)!, completionHandler: {(data, response, error) ->
Void in
let jsonData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)
print(jsonData!)
}).resume()
}
var jobToUrl = URL(string: "http://www.indeed.com/viewjob?jk=5de353a4c580dce0&qd=8FiWEXDXvmdNb_GJC9BAOpLFMiNO7rztIOPtGp_-cISTa1VWcmBigetsBoobMSCXdNyr-z6ge7UiYg2Mx15EH6m1Aj3izkOw87NHJgxznYA&indpubnum=9727336427429597&atk=1bchrhjof5hgga1k")
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
print("USER SELECTED CELL")
let JobUrl = jobUrlArray[indexPath.row]
**let safariVC = SFSafariViewController(url: JobUrl as URL)**
self.present(safariVC, animated: true, completion: nil)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return jobTitleArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell
cell.jobTitle.text = jobTitleArray[indexPath.row]
cell.jobSummary.text = snippetArray[indexPath.row]
cell.employerName.text = companyArray[indexPath.row]
cell.cityName.text = cityArray[indexPath.row]
cell.ApplyButton.text = jobUrlArray[indexPath.row]
// let imageUrl = NSURL(string: imageUrlArray[indexPath.row])
// if imageUrl != nil {
// let data = NSData(contentsOf: (imageUrl as? URL)!)
// cell.imageView?.image = UIImage (data: data as! Data)
// }
return cell
}
}
You can't cast a string to a URL. Casting simply says "Ok, the thing in this box. It's not a string, it's an URL." If the object can't double as the other class, the cast fails.
You need to create a URL using a string as input:
let url = URL(string: myString)
String and URL are not related therefore cannot be casted to each other. You have to create the URL from a string (like in another line in the code).
let safariVC = SFSafariViewController(url: URL(string: JobUrl)!)
Don't use NSURL in Swift 3 at all.
PS: Be aware that all optional bindings in downloadJsonWithURL are meaningless if you are using multiple arrays as data source. If one value does not pass the binding the app will crash at the latest in cellForRow due to an out-of-range exception.
URL is an object which has different properties (like absoluteString,path, scheme etc. which are String objects themselves) so you cannot cast URL to String, they are different types.
With an URL you can use the URLSession class to access the contents of remote resource or represent a local path for example. Check the documentation and be sure that you know the classes you're using.
https://developer.apple.com/reference/foundation/nsurl
In Swift try to create a URL with String (through unwrapping):
if let url = URL(String: jobUrlArray[indexPath.row]) {
let safariVC = SFSafariViewController(url: jobUrl)
}
or use url? in code
but be sure you don't use explicitly unwrapped optional like:
let safariVC = SFSafariViewController(url: URL(string: JobUrl)!)
your code might crash, it's not safe.

Fix JSON Parsing Scale Imageview tableview

I build project tableview with Json parsing. My project its work, but my imageview is spread. Before I already setting constraint for it image
Can someone help me how to make image to scale fit with constraint setting
My code:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
final let urlString = "http://wisatasumbar.esy.es/restful/search_articles.php?&keyword=bukittinggi"
#IBOutlet weak var tableView: UITableView!
var wisataArr = [String]()
var titleArr = [String]()
var imgUrlArr = [String]()
override func viewDidLoad() {
super.viewDidLoad()
self.downloadJsonWithURL()
}
func downloadJsonWithURL () {
let url = NSURL(string: urlString)
URLSession.shared.dataTask(with: (url as? URL)!, completionHandler: { (data, response, error) -> Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
print(jsonObj!.value(forKey: "data"))
if let dataArray = jsonObj!.value(forKey: "data") as? NSArray {
for data in dataArray{
if let dataDict = data as? NSDictionary{
if let title = dataDict.value(forKey: "title"){
self.titleArr.append(title as! String)
}
if let title = dataDict.value(forKey: "category"){
self.wisataArr.append(title as! String)
}
if let title = dataDict.value(forKey: "image_satu"){
self.imgUrlArr.append(title as! String)
}
}
}
}
OperationQueue.main.addOperation({
self.tableView.reloadData()
})
}
}).resume()
}
func downloadJsonWitTask () {
let url = NSURL(string: urlString)
var downloadTask = URLRequest(url: (url as? URL)!, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 20)
downloadTask.httpMethod = "GET"
URLSession.shared.dataTask(with: downloadTask, completionHandler: { (data, response, error) -> Void in
let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)
print(jsonObj)
}).resume()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return titleArr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell
cell.lblTitle.text! = titleArr[indexPath.row]
cell.lblWisata.text! = wisataArr[indexPath.row]
let imgUrl = NSURL(string: imgUrlArr[indexPath.row])
if imgUrl != nil {
let data = NSData(contentsOf: imgUrl as! URL)
cell.imgView.image = UIImage(data: data as! Data)
}
return cell
}
}
and this my app:
View Project Running

NSURLSession.sharedSession().dataTaskWithRequest runs slow in function

My problem arises when I want to populate data from my mysql database into a class object. I am trying to return an array of objects and it returns nil and then it fills itself somehow. How can I make it fill before returning the blank array?
Here is my code and a screenshot of code output
import Foundation
class Research
{
var mainResearchImageURL:String = ""
var userProfileImageURL:String = ""
var caption:String = ""
var shortDescription:String = ""
init(mainResearchImageURL :String, userProfileImageURL:String, caption:String, shortDescription:String)
{
self.mainResearchImageURL = mainResearchImageURL
self.userProfileImageURL = userProfileImageURL
self.caption = caption
self.shortDescription = shortDescription
}
class func downloadAllResearches()->[Research]
{
var researches = [Research]()
let urlString = "http://localhost/test/index.php"
let request = NSMutableURLRequest(URL: NSURL(string: urlString)!)
request.HTTPMethod = "POST"
let postString = "action=listresearches"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: {data, response, error in
if (error == nil) {
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSArray
//let dictionary = json!.firstObject as? NSDictionary
var counter:Int = 0;
for line in json!{
let researchData = line as! NSDictionary
let researchLineFromData = Research(mainResearchImageURL: researchData["research_mainImageURL"] as! String, userProfileImageURL: researchData["research_creatorProfileImageURL"] as! String, caption: researchData["research_caption"] as! String, shortDescription: researchData["research_shortDescription"] as! String)
researches.append(researchLineFromData) //researches bir dizi ve elemanları Research türünde bir sınıftan oluşuyor.
counter += 1
print ("counter value \(counter)")
print("array count in loop is = \(researches.count)")
}
}catch let error as NSError{
print(error)
}
} else {
print(error)
}})
task.resume()
print("array count in return is = \(researches.count)")
return researches
}
}
And this is the output:
add this on you completionHandler ( it works if you update a view)
dispatch_async(dispatch_get_main_queue(), {
if (error == nil) { ...... }
})
Advice 1:
return the task and use a completion param in your method,
you can cancel the task if it's too slow.
Advice 2 :
Use alamofire and swiftyJson framework
What happen here is that you are returning the value before finish (remember that the call is Asynchronous), you can make something like this:
class func downloadAllResearches(success:([Research])->Void,failure:(String)->Void)
{
var researches = [Research]()
let urlString = "http://localhost/test/index.php"
let request = NSMutableURLRequest(URL: NSURL(string: urlString)!)
request.HTTPMethod = "POST"
let postString = "action=listresearches"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: {data, response, error in
if (error == nil) {
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSArray
//let dictionary = json!.firstObject as? NSDictionary
var counter:Int = 0;
for line in json!{
let researchData = line as! NSDictionary
let researchLineFromData = Research(mainResearchImageURL: researchData["research_mainImageURL"] as! String, userProfileImageURL: researchData["research_creatorProfileImageURL"] as! String, caption: researchData["research_caption"] as! String, shortDescription: researchData["research_shortDescription"] as! String)
researches.append(researchLineFromData) //researches bir dizi ve elemanları Research türünde bir sınıftan oluşuyor.
counter += 1
print ("counter value \(counter)")
print("array count in loop is = \(researches.count)")
}
success(researches)
}catch let error as NSError{
print(error)
failure("Can be extract from NSERROR")
}
} else {
print(error)
failure("Error - Can be extract for NSERROR")
}})
task.resume()
}
And for call this Fuction use something like this:
Research.downloadAllResearches({ (objects:[Research]) -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
//Do whatever you like with the content
})
}) { (failureLiteral:String) -> Void in
}

Resources