xcode 9 webview with side menu - xcode

I need a side menu with table view and in it I need to get names from json file with links, in menu it must show names from json file and when I tap name i must open the url in my web view.
Alsow I need instead of json file, json url example, please help me
here is the link to my project
https://ufile.io/7qpzq

import UIKit
class SideMenuVC: UITableViewController {
final let urlString = "http://www.mocky.io/v2/5a02ad1d330000292bf6efa0"
var nameArray = [String]()
var iconArray = [String]()
var URLArray = [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: "menuItems") as Any)
if let menuArray = jsonObj!.value(forKey: "menuItems") as? NSArray {
for menuItems in menuArray{
if let menuDict = menuItems as? NSDictionary {
if let name = menuDict.value(forKey: "name") {
self.nameArray.append(name as! String)
}
if let icon = menuDict.value(forKey: "icon") {
self.iconArray.append(name as! String)
}
if let url = menuDict.value(forKey: "url") {
self.URLArray.append(name 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: downloadTask, completionHandler: {(data, response, error) -> Void in
let jsonData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)
print(jsonData as Any)
}).resume()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return nameArray.count
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
_ = nameArray[indexPath.row]
tableView.deselectRow(at: indexPath, animated: true)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "menu", for: indexPath)
let label = cell.viewWithTag(1000) as! UILabel
label.text = nameArray[indexPath.row]
return cell
}

Related

Voice Recorder: speaker playback by default

I've created a voice recorder that plays back through the earpiece; however, I want to play back by speaker. I've added the following (Swift 4):
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.overrideOutputAudioPort(AVAudioSession.PortOverride.speaker)
} catch let error as NSError {
print("Audio Session error: \(error.localizedDescription)")
}
When I initialize the app, I am able to playback previous recordings by speaker; however, as soon as I record a new voice memo, the playback goes back to earpiece. I've looked up solutions but they all refer to setCategory which throws an error in Swift 4.
Does anyone know how to default recorded playbacks to speaker?
Here is my view controller in full:
import UIKit
import AVFoundation
class ViewController2: UIViewController, AVAudioRecorderDelegate, UITableViewDelegate, UITableViewDataSource {
// Setting up Table View
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return numberOfRecords
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = String(indexPath.row + 1)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let path = getDirectory().appendingPathComponent("\(indexPath.row + 1).m4a")
do {
audioPlayer = try AVAudioPlayer(contentsOf: path)
audioPlayer.play()
}
catch {
}
}
var audioPlayer : AVAudioPlayer!
var recordingSession : AVAudioSession!
var audioRecorder : AVAudioRecorder!
var numberOfRecords : Int = 0
#IBOutlet weak var buttonLabel: UIButton!
#IBOutlet weak var myTableView: UITableView!
#IBAction func record(_ sender: Any) {
// Check if we have an active recorder
if audioRecorder == nil {
numberOfRecords += 1
let filename = getDirectory().appendingPathComponent("\(numberOfRecords).m4a")
let settings = [AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
AVSampleRateKey: 12000,
AVNumberOfChannelsKey: 1,
AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue]
// Start audio recording
do {
audioRecorder = try AVAudioRecorder(url: filename, settings: settings)
audioRecorder.delegate = self
audioRecorder.record()
//buttonLabel.setTitle("Stop", for: .normal)
}
catch {
displayAlert(title: "Oops!", message: "Recording failed")
}
}
else {
// Stop audio recording
audioRecorder.stop()
audioRecorder = nil
UserDefaults.standard.set(numberOfRecords, forKey: "myNumber")
myTableView.reloadData()
//buttonLabel.setTitle("Start", for: .normal)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Setting up Recording session
recordingSession = AVAudioSession.sharedInstance()
if let number : Int = UserDefaults.standard.object(forKey: "myNumber") as? Int {
numberOfRecords = number
}
AVAudioSession.sharedInstance().requestRecordPermission { (hasPermission) in
if hasPermission {
print ("Accepted")
}
}
// Play speaker instead of earpiece
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.overrideOutputAudioPort(AVAudioSession.PortOverride.speaker)
} catch let error as NSError {
print("Audio Session error: \(error.localizedDescription)")
}
// Gesture recognizers
let leftSwipe = UISwipeGestureRecognizer(target: self, action: #selector(swipeAction(swipe:)))
leftSwipe.direction = UISwipeGestureRecognizer.Direction.left
self.view.addGestureRecognizer(leftSwipe)
let rightSwipe = UISwipeGestureRecognizer(target: self, action: #selector(swipeAction(swipe:)))
rightSwipe.direction = UISwipeGestureRecognizer.Direction.right
self.view.addGestureRecognizer(rightSwipe)
let upSwipe = UISwipeGestureRecognizer(target: self, action: #selector(swipeAction(swipe:)))
upSwipe.direction = UISwipeGestureRecognizer.Direction.up
self.view.addGestureRecognizer(upSwipe)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Function that gets path to directory
func getDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentDirectory = paths[0]
return documentDirectory
}
// Function that displays an alert
func displayAlert(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "dismiss", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
}
The do catch statement needs to be within the if and not else and not in the viewDidLoad () section.
// Setting up Table View
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return numberOfRecords
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = String(indexPath.row + 1)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let path = getDirectory().appendingPathComponent("\(indexPath.row + 1).m4a")
do {
audioPlayer = try AVAudioPlayer(contentsOf: path)
audioPlayer.play()
}
catch {
}
}
var audioPlayer : AVAudioPlayer!
var recordingSession : AVAudioSession!
var audioRecorder : AVAudioRecorder!
var numberOfRecords : Int = 0
#IBOutlet weak var buttonLabel: UIButton!
#IBOutlet weak var myTableView: UITableView!
#IBAction func record(_ sender: Any) {
// Check if we have an active recorder
if audioRecorder == nil {
numberOfRecords += 1
let filename = getDirectory().appendingPathComponent("\(numberOfRecords).m4a")
let settings = [AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
AVSampleRateKey: 12000,
AVNumberOfChannelsKey: 1,
AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue]
// Start audio recording
do {
audioRecorder = try AVAudioRecorder(url: filename, settings: settings)
audioRecorder.delegate = self
audioRecorder.record()
//buttonLabel.setTitle("Stop", for: .normal)
}
catch {
displayAlert(title: "Oops!", message: "Recording failed")
}
// Play speaker instead of earpiece
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.overrideOutputAudioPort(AVAudioSessionPortOverride.speaker)
} catch let error as NSError {
print("Audio Session error: \(error.localizedDescription)")
}
}
else {
// Stop audio recording
audioRecorder.stop()
audioRecorder = nil
UserDefaults.standard.set(numberOfRecords, forKey: "myNumber")
myTableView.reloadData()
//buttonLabel.setTitle("Start", for: .normal)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Setting up Recording session
recordingSession = AVAudioSession.sharedInstance()
if let number : Int = UserDefaults.standard.object(forKey: "myNumber") as? Int {
numberOfRecords = number
}
AVAudioSession.sharedInstance().requestRecordPermission { (hasPermission) in
if hasPermission {
print ("Accepted")
}
}
// Gesture recognizers
let leftSwipe = UISwipeGestureRecognizer(target: self, action: #selector(swipeAction(swipe:)))
leftSwipe.direction = UISwipeGestureRecognizerDirection.left
self.view.addGestureRecognizer(leftSwipe)
let rightSwipe = UISwipeGestureRecognizer(target: self, action: #selector(swipeAction(swipe:)))
rightSwipe.direction = UISwipeGestureRecognizerDirection.right
self.view.addGestureRecognizer(rightSwipe)
let upSwipe = UISwipeGestureRecognizer(target: self, action: #selector(swipeAction(swipe:)))
upSwipe.direction = UISwipeGestureRecognizerDirection.up
self.view.addGestureRecognizer(upSwipe)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Function that gets path to directory
func getDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentDirectory = paths[0]
return documentDirectory
}
// Function that displays an alert
func displayAlert(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "dismiss", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
}

blank result in resultController with UISearchController

i use 2 tableViewController with custom prototype in each (one for search, one for result)
I have in console (print...) the good result, but my custom cell are blanck
here is my code if someone could help
Ty
import UIKit
class search_TableViewController: UITableViewController, UISearchResultsUpdating {
#IBOutlet var sTableView: UITableView!
// Properties
// 1
var users:[[String:AnyObject]]!
var foundUsers:[[String:AnyObject]]!
// 2
var userDetails:[String:AnyObject]!
// 3
var resultController: UITableViewController!
var searchController: UISearchController!
override func viewDidLoad() {
super.viewDidLoad()
users = []
foundUsers = []
self.sTableView.dataSource = self
self.sTableView.delegate = self
self.automaticallyAdjustsScrollViewInsets = false
//ViewDidLoad
let storyboard = UIStoryboard(name: "Main", bundle: nil)
resultController = storyboard.instantiateViewControllerWithIdentifier("resultId") as! UITableViewController
resultController.tableView.delegate = self;
resultController.tableView.dataSource = self
resultController.tableView.delegate = self;
resultController.tableView.registerClass(result_TableViewCell.self, forCellReuseIdentifier: "resultPRTC")
// 3
searchController = UISearchController(searchResultsController: resultController)
searchController.hidesNavigationBarDuringPresentation = true
searchController.searchBar.searchBarStyle = .Minimal
searchController.searchResultsUpdater = self
self.sTableView.tableHeaderView = searchController.searchBar
// 4
self.definesPresentationContext = true
// 5
let session = NSURLSession.sharedSession()
let url:NSURL! = NSURL(string: "http://jsonplaceholder.typicode.com/users")
let task = session.downloadTaskWithURL(url) { (location: NSURL?, response: NSURLResponse?, error: NSError?) -> Void in
if (location != nil){
let data:NSData! = NSData(contentsOfURL: location!)
do{
self.users = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves) as! [[String : AnyObject]]
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.sTableView.reloadData()
})
}catch{
// Catch any exception
print("Something went wrong")
}
}else{
// Error
print("An error occurred \(error)")
}
}
// Start the download task
task.resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: UISearchResultsUpdating
func updateSearchResultsForSearchController(searchController: UISearchController) {
foundUsers.removeAll()
for user in users{
let userName:String! = user["name"] as? String
if userName.localizedCaseInsensitiveContainsString(searchController.searchBar.text!) {
foundUsers.append(user)
print ("Liste 1 : \(foundUsers)")
self.resultController.tableView.reloadData()
}
}
}
//MARK: UITableViewDataSource
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//print (tableView)
if tableView == self.sTableView{
print ("userSearch :\(users.count)")
return users.count
}
//passe sur la recherche
print ("userResult:\(foundUsers.count)")
return foundUsers.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cellIdentifier: String!
var dic: [String:AnyObject]!
if tableView == self.sTableView{
cellIdentifier = "searchPRTC"
dic = self.users[indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! search_TableViewCell
cell.sNom?.text = dic["name"] as? String
cell.sEmail?.text = dic["email"] as? String
return cell
}else{
cellIdentifier = "resultPRTC"
dic = self.foundUsers[indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! result_TableViewCell
cell.rNom?.text = dic["name"] as? String
print ("Liste 2 : \(foundUsers)")
return cell
}
// let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath)
//cell.textLabel?.text = dic["name"] as? String
// cell.adresse?.text = dic["username"] as? String
}
}
If i use for result this code instead of my custom prototype i see the result - maybe this information could help a lot :
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath)
cell.textLabel?.text = dic["name"] as? String
i had it :
must delete this !
resultController.tableView.registerClass(result_TableViewCell.self, forCellReuseIdentifier: "resultPRTC")
Is someone know if it's possible to have only one view ? or i must have 2 tableview controller (one for search one for result)
ty

swift collectionview in tableview load images horizontally in collectionview

I need horizontal images in collectionview, which is inside every tableview cell. The problem I am facing is tableview gets loaded easily, but collectionview doesn't get loaded before tableview cells, because tableview loads very quickly, and hence the array for collectionview gets changed.
The code I am using for the whole view, is -
import UIKit
class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,NSURLConnectionDelegate {
#IBOutlet var tbl_data: UITableView!
var mutableData: NSMutableData!
var response: NSURLResponse!
var connection: NSURLConnection!
var thedata:NSArray!
var ary_OF_collectionView:NSArray!
override func viewDidLoad() {
super.viewDidLoad()
connection_GetPeopleList()
thedata = NSArray()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// Return the number of sections.
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return thedata.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
//println("INdex===\(indexPath.row)")
let cell = tableView.dequeueReusableCellWithIdentifier("dTableViewCell", forIndexPath: indexPath) as! dTableViewCell
var c_snippet:String = ""
if let checkC_snip:AnyObject = thedata.objectAtIndex(indexPath.row).valueForKey("c_snippet")
{
c_snippet = checkC_snip as! String
}
var getImageArray:NSArray = (thedata.objectAtIndex(indexPath.row).valueForKey("images") as? NSArray)!
cell.lbl_like.text = c_snippet
cell.co_v.tag = indexPath.row
if(getImageArray.count > 0)
{
if(getImageArray.count == 1)
{
var getimagePath:String = getImageArray.objectAtIndex(0) as! String
if(!getimagePath.isEmpty)
{
ary_OF_collectionView = getImageArray
}else
{
ary_OF_collectionView = NSArray()
}
}else
{
ary_OF_collectionView = getImageArray
}
}else
{
ary_OF_collectionView = NSArray()
}
cell.co_v.dataSource = self
cell.co_v.delegate = self
cell.co_v.reloadData()
cell.selectionStyle = UITableViewCellSelectionStyle.None
return cell
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return ary_OF_collectionView.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionViewCell", forIndexPath: indexPath) as! CollectionViewCell
var getImageUrl:String! = ary_OF_collectionView.objectAtIndex(indexPath.row) as! String
println(getImageUrl)
// This is image loader From == https://github.com/natelyman/SwiftImageLoader
ImageLoader.sharedLoader.imageForUrl(getImageUrl, completionHandler:{(image: UIImage?, url: String) in
cell.img.image = image
})
//cell.img.image = UIImage(named: ) as UIImage!
return cell
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath)
{
println("INinininin===\(indexPath.row)")
// var cell:dTableViewCell = cell as! dTableViewCell
// [cell setCollectionViewDataSourceDelegate:self index:indexPath.row];
}
func scrollViewDidScroll(scrollView: UIScrollView) {
println(scrollView)
// println("INinininin===\(scrollView.tag)")
}
func connection_GetPeopleList()
{
let urlPath: String = "http://carbonchase.com/v1.1/get_jives.php?user_id=3221128362&at=0&newsfeeds&count=10"
println("get_People List == \(urlPath)")
var escapedAddress = urlPath.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
var url: NSURL = NSURL(string: escapedAddress!)!
var request1: NSURLRequest = NSURLRequest(URL: url)
self.connection = NSURLConnection(request: request1, delegate: self, startImmediately: true);
connection.start()
}
func connection(connection: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
self.response = response
self.mutableData = NSMutableData()
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!) {
self.mutableData.appendData(data)
}
func connectionDidFinishLoading(connection: NSURLConnection!)
{
if let jsonResult: NSArray = NSJSONSerialization.JSONObjectWithData(self.mutableData, options: nil, error:nil) as? NSArray {
thedata = jsonResult
self.tbl_data.reloadData();
self.tbl_data.delegate=self;
self.tbl_data.dataSource=self;
}
}
func connection(connection: NSURLConnection, didFailWithError error: NSError) {
println("\(error)")
}
}// END
EDITED
CollectionView is not working

Why is my Swift string variable returning nil?

I am trying to use Parse to create a simple tableview that triggers the URLs of PDF documents that I have uploaded to the Parse Cloud.
In the code below, my variable thePDFFile does output a URL correctly to the console. But when I try to return that variable, it comes up nil and the app crashes.
I am pretty sure that I am not unwrapping an optional correctly, but I can't see where.
The function with the error is named GrabPDF()->String.
import UIKit
import Parse
import Bolts
import AVFoundation
import AVKit
public var AudioPlayer = AVPlayer()
public var SelectedSong = Int()
var theFile:String!
var thePDFFile:String!
class TableViewController: UITableViewController, AVAudioPlayerDelegate {
var iDArray = [String]()
var NameArray = [String]()
var PDFArray = [String]()
var PDFFileArray = [PFObject]()
override func viewDidLoad() {
super.viewDidLoad()
var ObjectIDQuery = PFQuery(className:"Recordings")
ObjectIDQuery.findObjectsInBackgroundWithBlock({
(objectsArray : [AnyObject]?, error: NSError?) -> Void in
var objectIDs = objectsArray as! [PFObject]
for i in 0...objectIDs.count-1{
self.iDArray.append(objectIDs[i].valueForKey("objectId") as! String)
self.NameArray.append(objectIDs[i].valueForKey("RecordingName") as! String)
self.PDFArray.append(objectIDs[i].valueForKey("PDFFileName") as! String)
self.tableView.reloadData()
}
})
}
func grabSong() {
var SongQuery = PFQuery(className:"Recordings")
SongQuery.getObjectInBackgroundWithId(iDArray[SelectedSong], block: {
(object : PFObject?, error : NSError?) -> Void in
if let AudioFileURLTemp = object?.objectForKey("RecordingFile")?.url {
AudioPlayer = AVPlayer(URL: NSURL(string: AudioFileURLTemp!))
AudioPlayer.play()
theFile = AudioFileURLTemp
}
})
}
func grabPDF() -> String {
var PDFQuery = PFQuery(className:"Recordings")
PDFQuery.getObjectInBackgroundWithId(iDArray[SelectedSong], block: {
(object: PFObject?, error : NSError?) -> Void in
if let PDFFileURLTemp = object?.objectForKey("PDFFile")?.url {
println(PDFFileURLTemp)
let thePDFFile = PDFFileURLTemp! as String
println("The value of thePDFFile is \(thePDFFile)")
}
})
return thePDFFile
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return iDArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! UITableViewCell
cell.textLabel?.text = NameArray[indexPath.row]
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
SelectedSong = indexPath.row
grabSong()
grabPDF()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "WebView" {
if let VC2 = segue.destinationViewController as? WebViewController {
if let indexPath = tableView.indexPathForSelectedRow()?.row {
VC2.sentData = theFile
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
You're shadowing thePDFFile with that let. The shadow is popped off the stack when you pass the closing brace and you're returning the instance variable which was not set

Wrong image retrived from Parse, Asynchronous

Folks. I got a problem with parse, i got an image from Parse, but images are wrong, sometimes appear the same image, other, appear wrong images, and I don't know what's happening, somebody help me! I'm a newbie in Parse and Swift. Thanks!
import UIKit
import Parse
import Bolts
import Bolts
import Parse
class LojasViewController: UIViewController, UITableViewDelegate {
var ParseData = [PFObject]()
var dataObjects = [NSData]()
var photoArray: Array<UIImage> = []
var ImagemCelula = UIImage()
#IBOutlet weak var saloesTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
GetParse()
}
override func viewDidAppear(animated: Bool) {
// Refresh the table to ensure any data changes are displayed
saloesTableView.reloadData()
}
// Retrieve from Parse
func GetParse() {
var query:PFQuery = PFQuery(className:"Saloes")
query.orderByAscending("nome")
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
if let object = objects as? [PFObject] {
self.ParseData = object
println(self.ParseData.count)
println(self.ParseData)
self.saloesTableView.reloadData()
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Esconde statusBar
override func prefersStatusBarHidden() -> Bool {
return true
}
#IBAction func voltarButton(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
// MARK: - Table view data source ____________________________________
func numberOfSectionsInTableView(tableView: UITableView!) -> Int
{
return 1
}
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int
{
return ParseData.count
}
func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell?
{
let cell:SaloesTableViewCell = tableView!.dequeueReusableCellWithIdentifier("Cell",forIndexPath: indexPath!) as! SaloesTableViewCell
cell.nomeSalao.text = ParseData[indexPath!.row]["nome"] as? String
for object in ParseData {
let ImageFile = object["imagemCelula"] as! PFFile
ImageFile.getDataInBackgroundWithBlock { (imageData: NSData?, error: NSError?) -> Void in
if let imageData = imageData where error == nil
{
self.ImagemCelula = UIImage(data: imageData)!
cell.imagemSalao.image = self.ImagemCelula
}
}
}
return cell
}
First of all, you must create a new array, for example:
var images = [NSData]()
or PFFile, UIImage etc...
var query = PFUser.query()
query!.whereKey("yourWherekey", equalTo: "your where value")
query?.findObjectsInBackgroundWithBlock{
(results: [AnyObject]?, error) -> Void in
if results != nil {
for result in results!
{
self.images.append(result["image"] as! NSData)
self.tableView.reloadData() // important
}
}
}
Append to images to Images Array.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cellA", forIndexPath: indexPath) as! UITableViewCell
cell.textLabel?.text = "TEST STRING"
cell.imageView?.image = UIImage(data: images[indexPath.row])
return cell
}
And connect with indexPath.row. I coded with NSData if you want you can code with PFFile

Resources