Voice Recorder: speaker playback by default - xcode

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)
}

Related

xcode 9 webview with side menu

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
}

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

How can I add a top margin to my tableview in Xcode?

I'm trying to add an image on the very top of the first cell of a table view. How can i make the table view have a top margin? Right now, the image is just overlapping the tableview. I am trying to just get the table view to come down a little bit. I do not want to make it smaller or something like that. I just want to add a button to the top of the tableview.
//
// usersVC.swift
// CaastRun
//
// Created by Computer on 5/23/15.
// Copyright (c) 2015 Caast. All rights reserved.
//
import UIKit
class usersVC: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var resultsTable: UITableView!
var resultsNameArray = [String]()
var resultsUserNameArray = [String]()
var resultsImageFiles = [PFFile]()
override func viewDidLoad() {
super.viewDidLoad()
let theWidth = view.frame.size.width
let theHeight = view.frame.size.height
resultsTable.frame = CGRectMake(0, 0, theWidth, theHeight)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(animated: Bool) {
resultsNameArray.removeAll(keepCapacity: false)
resultsUserNameArray.removeAll(keepCapacity: false)
resultsImageFiles.removeAll(keepCapacity: false)
var query = PFUser.query()
query!.whereKey("username", notEqualTo: PFUser.currentUser()!.username!)
query!.findObjectsInBackgroundWithBlock {
(objects:[AnyObject]?, error:NSError?) -> Void in
if error == nil {
for object in objects! {
self.resultsNameArray.append(object.objectForKey("profileName") as! String)
self.resultsImageFiles.append(object.objectForKey("photo") as! PFFile)
self.resultsUserNameArray.append(object.objectForKey("username") as! String)
self.resultsTable.reloadData()
}
}
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return resultsNameArray.count
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 64
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:usersCell = tableView.dequeueReusableCellWithIdentifier("Cell") as! usersCell
cell.profileLbl.text = self.resultsNameArray[indexPath.row]
cell.usernameLbl.text = self.resultsUserNameArray[indexPath.row]
var query = PFQuery(className: "follow")
query.whereKey("user", equalTo: PFUser.currentUser()!.username!)
query.whereKey("userToFollow", equalTo: cell.usernameLbl.text!)
query.countObjectsInBackgroundWithBlock {
(count:Int32, error:NSError?) -> Void in
if error == nil {
if count == 0 {
cell.followBtn.setTitle("Follow", forState: UIControlState.Normal)
} else {
cell.followBtn.setTitle("Following", forState: UIControlState.Normal)
}
}
}
self.resultsImageFiles[indexPath.row].getDataInBackgroundWithBlock {
(imageData:NSData?, error:NSError?) -> Void in
if error == nil {
let image = UIImage(data: imageData!)
cell.imgView.image = image
}
}
return cell
}
#IBOutlet weak var searchText: UITextField!
#IBAction func searchButton(sender: AnyObject) {
resultsNameArray.removeAll(keepCapacity: false)
resultsUserNameArray.removeAll(keepCapacity: false)
resultsImageFiles.removeAll(keepCapacity: false)
var query = PFUser.query()
query!.whereKey("username", notEqualTo: PFUser.currentUser()!.username!)
query!.whereKey("profileName", containsString: self.searchText.text)
query!.findObjectsInBackgroundWithBlock {
(objects:[AnyObject]?, error:NSError?) -> Void in
if error == nil {
for object in objects! {
self.resultsNameArray.append(object.objectForKey("profileName") as! String)
self.resultsImageFiles.append(object.objectForKey("photo") as! PFFile)
self.resultsUserNameArray.append(object.objectForKey("username") as! String)
self.resultsTable.reloadData()
}
}
}
}
}
I am not sure if I understand your question, if you are trying to have a margin between your table and the view try this:
Swift 3
self.tableView.contentInset = UIEdgeInsets(top: 20,left: 0,bottom: 0,right: 0)
Swift 2
self.tableView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0);

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