Asynchronously Downloading The Image From Parse - image

I'm trying to download images from parse via 'Asynchronously'.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell? {
var cell:CatsTableViewCell? = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? CatsTableViewCell
if(cell == nil) {
cell = NSBundle.mainBundle().loadNibNamed("CatsTableViewCell", owner: self, options: nil) [0] as? CatsTableViewCell
}
if let pfObject = object {
cell?.catNameLabel?.text = pfObject["name"] as? String
var votes:Int? = pfObject["votes"] as? Int
if votes == nil {
votes = 0
}
cell?.catVotesLabel?.text = "\(votes!) votes"
var credit:String? = pfObject["cc_by"] as? String
if credit != nil {
cell?.catCreditLabel?.text = "\(credit!) / CC 2.0"
}
cell?.catImageView?.image = nil
if var urlString:String? = pfObject["url"] as? String {
var url:NSURL? = NSURL(string: urlString!)
if var url:NSURL? = NSURL(string: urlString!) {
var error:NSError?
var request:NSURLRequest = NSURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReturnCacheDataElseLoad, timeoutInterval: 5.0)
NSOperationQueue.mainQueue().cancelAllOperations()
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {
(response:NSURLResponse?, imageData:NSData?, error:NSError?) -> Void in
cell?.catImageView?.image = UIImage(data: imageData!)
})
}
}
now I changed few code
completionHandler: {
(response:NSURLResponse!, imageData:NSData!, error:NSError!) -> Void in
cell?.catImageView?.image = UIImage(data: imageData)
to
completionHandler: {
(response:NSURLResponse?, imageData:NSData?, error:NSError?) -> Void in
cell?.catImageView?.image = UIImage(data: imageData!)
and no critical errors but the image doesn't show up on the simulator.
Any help would be appreciate. Thank you all.
-first problem-
*And the problem is occurred down below
cell?.catImageView?.image = UIImage(data: imageData)
it says
Value of optional type ‘()?’ not unwrapped; did you mean to use ‘!’ or ‘?’?*

The initializer init(data:) returns an optional UIImage. You should check and unwrap it:
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {
(response: NSURLResponse?, imageData: NSData?, error: NSError?) -> Void in
if let e = error {
print(e)
return
}
guard let data = imageData else { return }
if let image = UIImage(data: data) {
cell?.catImageView?.image = image
}
})

Related

Text bubble only two characters wide - JSQmessagesviewcontroller

Text bubble only allow 2character then create a new line break for the next 2 characters. this will happen randomly. I did not make any adjustments to the bubble characters it just appears like that. Thank you in advance for the help
import UIKit
import JSQMessagesViewController
import MobileCoreServices
import AVKit
import Firebase
import Braintree
class messagesViewController: JSQMessagesViewController {
//braintree info
var braintreeClient: BTAPIClient?
var clientToken = String()
var formInfo = [String: AnyObject]()
// this is the id of the post id number
var previousViewMessageId:String!
)
var messages = [JSQMessage]()
//ref to retrieve message
var messageRef:FIRDatabaseReference! //
override func viewDidLoad() {
super.viewDidLoad()
//braintreeSetup()
navBar()
// tappedMyPayButton()
self.messageRef = fireBaseAPI().childRef("version_one/frontEnd/post/\(previousViewMessageId)")
let currentUser = fireBaseAPI().currentUserId()
self.senderId = currentUser
self.senderDisplayName = ""
let ref = fireBaseAPI().ref()
let messagRef = ref.child("version_one/frontEnd/post/\(previousViewMessageId)messages")
// messagRef.childByAutoId().setValue("first Message")
messagRef.observeEventType(.ChildAdded, withBlock: {snapshot in
//if let dict = snapshot.value as? String {
//}
})
observerveMessages()
}
}
extension messagesViewController {
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.messages.count
}
override func collectionView(collectionView: JSQMessagesCollectionView!, messageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageData! {
let data = self.messages[indexPath.row]
return data
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = super.collectionView(collectionView, cellForItemAtIndexPath: indexPath) as! JSQMessagesCollectionViewCell
return cell
}
override func collectionView(collectionView: JSQMessagesCollectionView!, didDeleteMessageAtIndexPath indexPath: NSIndexPath!) {
self.messages.removeAtIndex(indexPath.row)
}
override func collectionView(collectionView: JSQMessagesCollectionView!, messageBubbleImageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageBubbleImageDataSource! {
let bubbleFactory = JSQMessagesBubbleImageFactory()
let message = messages[indexPath.item]
if message.senderId == self.senderId {
return bubbleFactory.outgoingMessagesBubbleImageWithColor(UIColor(r: 43, g: 216, b: 225))
}else{
return bubbleFactory.incomingMessagesBubbleImageWithColor(UIColor(r: 125, g: 125, b: 125))
}
}
override func collectionView(collectionView: JSQMessagesCollectionView!, avatarImageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageAvatarImageDataSource! {
return nil
}
}
//MARK - image
extension messagesViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate {
override func didPressSendButton(button: UIButton!, withMessageText text: String!, senderId: String!, senderDisplayName: String!, date: NSDate!) {
let newMessage = messageRef.child("messages")
let messageData = ["text":text,"senderId":senderId,"senderDisplayName":senderDisplayName, "mediaType":"TEXT"]
newMessage.childByAutoId().setValue(messageData)
self.finishSendingMessage()
}
func observerveMessages(){
let obRef = fireBaseAPI().childRef("version_one/frontEnd/post/\(previousViewMessageId)/messages")
obRef.observeEventType(.ChildAdded, withBlock: {snapshot in
//
if let dict = snapshot.value as? [String:AnyObject]{
let mediaType = dict["mediaType"] as! String
let senderId = dict["senderId"] as! String
let senderName = dict["senderDisplayName"] as! String
switch mediaType {
case "TEXT":
let text = dict["text"] as? String
self.messages.append(JSQMessage(senderId: senderId, displayName: senderName, text: text))
case "PHOTO":
let fileUrl = dict["fileUrl"] as! String
let url = NSURL(string: fileUrl)
let data = NSData(contentsOfURL: url!)
let picture = UIImage(data: data!)
let photo = JSQPhotoMediaItem(image: picture!)
self.messages.append(JSQMessage(senderId: senderId,displayName: senderName, media: photo))
if self.senderId == senderId {
photo.appliesMediaViewMaskAsOutgoing = true
}else{
photo.appliesMediaViewMaskAsOutgoing = false
}
case "VIDEO":
let fileUrl = dict["fileUrl"] as! String
let video = NSURL(string: fileUrl)
let videoItem = JSQVideoMediaItem(fileURL: video, isReadyToPlay: true)
self.messages.append(JSQMessage(senderId: senderId,displayName:senderName,media: videoItem))
if self.senderId == senderId {
videoItem.appliesMediaViewMaskAsOutgoing = true
}else{
videoItem.appliesMediaViewMaskAsOutgoing = false
}
default :
print("Unknown data")
}
self.collectionView.reloadData()
}
})
}
override func didPressAccessoryButton(sender: UIButton!) {
let sheet = UIAlertController(title: "Media Messages", message: "Please select an images", preferredStyle: .ActionSheet)
let cancel = UIAlertAction(title: "Cancel", style: .Cancel) { (alert) in
}
let photoLibrary = UIAlertAction(title: "Photo Library", style: .Default) { (alert) in
self.getMediafrom(kUTTypeImage)
}
let VideoLibrary = UIAlertAction(title: "Video Library", style: .Default) { (alert) in
self.getMediafrom(kUTTypeMovie)
}
sheet.addAction(photoLibrary)
sheet.addAction(VideoLibrary)
sheet.addAction(cancel)
self.presentViewController(sheet, animated: true, completion: nil)
// let imagePicker = UIImagePickerController()
// imagePicker.delegate = self
// self.presentViewController(imagePicker, animated: true, completion: nil)
//
}
func getMediafrom(type:CFString){
let mediaPicker = UIImagePickerController()
mediaPicker.delegate = self
mediaPicker.mediaTypes = [type as String]
self.presentViewController(mediaPicker, animated: true, completion: nil)
}
// Display video message
override func collectionView(collectionView: JSQMessagesCollectionView!, didTapMessageBubbleAtIndexPath indexPath: NSIndexPath!) {
let message = messages[indexPath.item]
if message.isMediaMessage {
if let mediaItem = message.media as? JSQVideoMediaItem{
let player = AVPlayer(URL: mediaItem.fileURL)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.presentViewController(playerViewController, animated: true, completion: nil)
}
}
}
func sendMedia(picture:UIImage?,video: NSURL?){
let filePath = "frontEnd/users/\(fireBaseAPI().currentUserId()!)/images/\(NSDate.timeIntervalSinceReferenceDate())/"
if let picture = picture{
let data = UIImageJPEGRepresentation(picture, 0.1)
let metaData = FIRStorageMetadata()
metaData.contentType = "image/jpg"
FIRStorage.storage().reference().child(filePath).putData(data!, metadata: metaData) { (metaData, error) in
if error != nil {
print(error)
return
}
let fileUrl = metaData?.downloadURLs![0].absoluteString
let newMessage = self.messageRef.child("messages")
let messageData = ["fileUrl":fileUrl,"senderId":self.senderId,"senderDisplayName":self.senderDisplayName, "mediaType":"PHOTO"]
newMessage.childByAutoId().setValue(messageData)
}
}else if let video = video{
let data = NSData(contentsOfURL: video)
let metaData = FIRStorageMetadata()
metaData.contentType = "video/mp4"
FIRStorage.storage().reference().child(filePath).putData(data!, metadata: metaData) { (metaData, error) in
if error != nil {
print(error)
return
}
let fileUrl = metaData?.downloadURLs![0].absoluteString
let newMessage = self.messageRef.child("messages")
let messageData = ["fileUrl":fileUrl,"senderId":self.senderId,"senderDisplayName":self.senderDisplayName, "mediaType":"VIDEO"]
newMessage.childByAutoId().setValue(messageData)
}
}
}
//photothe
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if let picture = info[UIImagePickerControllerOriginalImage] as? UIImage{
// let photo = JSQPhotoMediaItem(image: picture)
//// messages.append(JSQMessage(senderId: senderId,displayName: senderDisplayName,media: photo))
sendMedia(picture,video:nil)
}else if let video = info[UIImagePickerControllerMediaURL] as? NSURL {
// let videoItem = JSQVideoMediaItem(fileURL: video, isReadyToPlay: true)
// messages.append(JSQMessage(senderId: senderId,displayName:senderDisplayName,media: videoItem))
sendMedia(nil, video: video)
}
self.dismissViewControllerAnimated(true, completion: nil)
collectionView.reloadData()
}
}
extension messagesViewController{
func dismissVc(){
self.dismissViewControllerAnimated(true, completion: nil)
}
//button setup
}
// button Actions

upload collection view images into server using swift

I'm developing an app which has UICollectionView as like #zhangao0086/DKImagePickerController# example in Github. Now i need to upload the displayed UICollectionviewCell images into server. Can any one suggest me the right tuts for uploading. Thanks in advance.
UICollectionView code as follows:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let asset = self.assets![indexPath.row]
var cell: UICollectionViewCell?
var imageView: UIImageView?
if asset.isVideo {
cell = collectionView.dequeueReusableCellWithReuseIdentifier("CellVideo", forIndexPath: indexPath)
imageView = cell?.contentView.viewWithTag(1) as? UIImageView
} else {
cell = collectionView.dequeueReusableCellWithReuseIdentifier("CellImage", forIndexPath: indexPath)
imageView = cell?.contentView.viewWithTag(1) as? UIImageView
}
if let cell = cell, imageView = imageView {
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
let tag = indexPath.row + 1
cell.tag = tag
asset.fetchImageWithSize(layout.itemSize.toPixel(), completeBlock: { image, info in
if cell.tag == tag {
imageView.image = image
}
})
}
return cell!
}
uploading the image into server
func barButtonItemClicked(barButtonItem: UIBarButtonItem)
{
let myUrl = NSURL(string: "http://moneymonkey.tokiiyo.com/api/signature");
let typeItem: InsuranceType = InsuranceManager.sharedInstance.TypeArray[0]
let compItem: Companies = InsuranceManager.sharedInstance.CompArray[0]
let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";
let param = [
"api_key" : "AiK58j67",
"api_secret" : "a#9rJkmbOea90-",
"phone" : "\(mobile)",
"policy_type" : "\(typeItem.name)",
"company" : "\(compItem.cname)"
]
print("Policy_type: \(typeItem.name)")
let boundary = generateBoundaryString()
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let imageData = UIImagePNGRepresentation(?) //here what imageView
if(imageData==nil) { return; }
request.HTTPBody = createBodyWithParameters(param, filePathKey: "file", imageDataKey: imageData!, boundary: boundary)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
// You can print out response object
print("******* response = \(response)")
// Print out reponse body
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("****** response data = \(responseString!)")
do{
_ = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
dispatch_async(dispatch_get_main_queue(),{
});
}
catch
{
// report error
print("Oops!! Something went wrong\(error)")
}
}
task.resume()
}
func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData {
let body = NSMutableData();
if parameters != nil {
for (key, value) in parameters! {
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString("\(value)\r\n")
}
}
let filename = "image.png"
let mimetype = "image/png"
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
body.appendString("Content-Type: \(mimetype)\r\n\r\n")
body.appendData(imageDataKey)
body.appendString("\r\n")
body.appendString("--\(boundary)--\r\n")
return body
}
func generateBoundaryString() -> String {
return "Boundary-\(NSUUID().UUIDString)"
}
J
you can use Alamofire https://github.com/Alamofire/Alamofire
Use like this :
Alamofire.upload(.POST, "YourURl", file: YourFile)
.progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in
print(totalBytesWritten)
// This closure is NOT called on the main queue for performance
// reasons. To update your ui, dispatch to the main queue.
dispatch_async(dispatch_get_main_queue()) {
print("Total bytes written on main queue: \(totalBytesWritten)")
}
}
.responseJSON { response in
debugPrint(response)
}

Need help adding name to qrcode so i can save to parse

I cannot figure out why im getting this error.
This is the function to update a guest(Participant). I'm trying to save the Qr code i created to a PFFile and save to parse.
func update() {
_ = LabelText
let query = PFQuery(className: "Participant")
query.getObjectInBackgroundWithId(LabelText) {
(Update: PFObject?, error: NSError?) -> Void in
Update!["firstname"] = self.firstnameTF!.text
Update!["lastname"] = self.lastnameTF!.text
Update!["grade"] = self.gradeTF!.text
Update!["teacher"] = self.teacherTF.text
Update!["email"] = self.emailTF.text
Update!["phone"] = self.phoneTF.text
Update!["transportation"] = self.transportationTF.text
Update!.saveInBackground()
print("updated")
if self.QrImage == nil {
print("Image is Blank")
return
}else{
//Image is not blank
let imageData = UIImageJPEGRepresentation(self.QrImage!, 1)
let parseImageFile = PFFile(data: imageData!)
Update!.setObject(parseImageFile!, forKey: "qrcode")
Update!.saveInBackgroundWithBlock( {
(success: Bool , error: NSError?) -> Void in
})
}
self.dismissViewControllerAnimated(true, completion: {});
}
}
I can see the image in the self.QrImage field and i only get the error on:
let parseImageFile = PFFile(data: imageData!)
Why am i getting a nil error when it should have a value there?
Edit 1:
let imageData = UIImagePNGRepresentation(self.QrImage!)
let parseImageFile = PFFile(data: imageData!)
Update!.setObject(parseImageFile!, forKey: "qrcode")
Update!.saveInBackgroundWithBlock( {
(success: Bool , error: NSError?) -> Void in
})
}
Same result."fatal error: unexpectedly found nil while unwrapping an Optional value"
Edit 2:
So it seems there must be a name value associated with the image before you upload it to parse. My Image is of a Qrcode i create from other data. here's my code:
func displayQrCode() {
print(self.qrdata.text)
let data = self.qrdata.text!.dataUsingEncoding(NSISOLatin1StringEncoding)
let filter = CIFilter(name: "CIQRCodeGenerator")
filter!.setValue(data, forKey: "inputMessage")
filter!.setValue("Q", forKey: "inputCorrectionLevel")
self.qrcodeImage = filter!.outputImage!
let scaleX = qrCode.frame.size.width / qrcodeImage!.extent.size.width
let scaleY = qrCode.frame.size.height / qrcodeImage!.extent.size.height
let transformedImage = qrcodeImage!.imageByApplyingTransform(CGAffineTransformMakeScale(scaleX, scaleY))
self.qrCode.image = UIImage(CIImage: transformedImage)
print("QRCode Made")
}
now i guess i need to add a name to the self.qrCode.image?
This is what needs to be done before you use UIImagePNGRepresentation:
self.QrImage = UIImage(named: "qrcode.png")

iOS 9(Swift 2.0): cannot invoke 'dataTaskwithURL' with an argument list of type '(NSURL, (_, _,_)throws -> Void)'

My app works perfectly fine with iOS 8 but yesterday I upgraded to iOS 9 and Xcode 7 then my app crashes. The error message is cannot invoke 'dataTaskwithURL' with an argument list of type '(NSURL, (_, ,)throws -> Void)'. I googled it and found a similar question here but the solution didn't really work (the solution was to add the do/catch blocks around the code). Can anyone help me with mine problem? Thank you!!!
Here's my code
import UIKit
import Foundation
import CoreLocation
class GoogleDataProvider {
let apiKey = "AIzaSyCQo-clIkek87N99RVh2lmFX9Mu9QPhAtA"
let serverKey = "AIzaSyBzmv7wPFcPAe1ucy5o6dqaXnda9i9MqjE"
var photoCache = [String:UIImage]()
var placesTask = NSURLSessionDataTask()
var session: NSURLSession {
return NSURLSession.sharedSession()
}
func fetchPlacesNearCoordinate(coordinate: CLLocationCoordinate2D, radius:Double, types:[String],keyword:String, completion: (([GooglePlace]) -> Void)) -> ()
{
var urlString = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?key=\(serverKey)&location=\(coordinate.latitude),\(coordinate.longitude)&radius=\(radius)&keyword=\(keyword)&rankby=prominence&sensor=true"
let typesString = types.count > 0 ? types.joinWithSeparator("|") : "food"
urlString += "&types=\(typesString)"
urlString = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
if placesTask.taskIdentifier > 0 && placesTask.state == .Running {
placesTask.cancel()
}
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
do{
//******************Here's the line that displays error
placesTask = session.dataTaskWithURL(NSURL(string: urlString)!) {
(data, response, error) -> Void in
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
var placesArray = [GooglePlace]()
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options:[]) as? NSDictionary {
if let results = json["results"] as? NSArray {
for rawPlace:AnyObject in results {
let place = GooglePlace(dictionary: rawPlace as! NSDictionary, acceptedTypes: types)
placesArray.append(place)
if let reference = place.photoReference {
self.fetchPhotoFromReference(reference) { image in
place.photo = image
}
}
}
}
}
dispatch_async(dispatch_get_main_queue()) {
completion(placesArray)
}
}
}catch{
}
placesTask.resume()
}
func fetchDirectionsFrom(from: CLLocationCoordinate2D, to: CLLocationCoordinate2D, completion: ((String?) -> Void)) -> ()
{
let urlString = "https://maps.googleapis.com/maps/api/directions/json?key=\(serverKey)&origin=\(from.latitude),\(from.longitude)&destination=\(to.latitude),\(to.longitude)&mode=walking"
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
do{
//******************************Here too ****************************
session.dataTaskWithURL(NSURL(string: urlString)!) {
(data, response, error) -> Void in
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
var encodedRoute: String?
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options:[]) as? [String:AnyObject] {
if let routes = json["routes"] as AnyObject? as? [AnyObject] {
if let route = routes.first as? [String : AnyObject] {
if let polyline = route["overview_polyline"] as AnyObject? as? [String : String] {
if let points = polyline["points"] as AnyObject? as? String {
encodedRoute = points
}
}
}
}
}
dispatch_async(dispatch_get_main_queue()) {
completion(encodedRoute)
}
}.resume()
}catch{
}
}
}
Sorry this is my first time posting the code style is a little bit confusing sorry about the indentation mess :)
Thanks again!!!
dataTaskWithURL:completionHandler: does not throw error.
Put do and catch inside dataTaskWithURL method.
for example:
session.dataTaskWithURL(NSURL(string: urlString)!) {
(data, response, error) -> Void in
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
var encodedRoute: String?
do {
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options:[]) as? [String:AnyObject] {
if let routes = json["routes"] as AnyObject? as? [AnyObject] {
if let route = routes.first as? [String : AnyObject] {
if let polyline = route["overview_polyline"] as AnyObject? as? [String : String] {
if let points = polyline["points"] as AnyObject? as? String {
encodedRoute = points
}
}
}
}
}
} catch {
}
dispatch_async(dispatch_get_main_queue()) {
completion(encodedRoute)
}
}.resume()

PFQueryTableView Controller not loading custom Cells

Im working on an app and I would like it to populate the cells based on users who are within a set distance from the currentuser. For some reason the customcells are not being populated with the correct objects. The labels and images that are supposed to be retrieved are blank. All i get is a blank cell. I made sure i gave the cell identifier the correct name, and i also made sure to link the tableviewcontroller and the tablecellview to their respective classes,but still no luck.
first i created initializers:
class TableViewController: PFQueryTableViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
var currLocation: CLLocationCoordinate2D?
override init!(style: UITableViewStyle, className: String!) {
super.init(style: style, className: className)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.parseClassName = "User"
self.textKey = "FBName"
// self.imageKey = "pictureURL"
self.pullToRefreshEnabled = true
self.objectsPerPage = 10
self.paginationEnabled = true
}
Then in viewDidLoad i enabled location services:
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.estimatedRowHeight = 200
self.locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
loadData()
println("location services enabled bruh")
}
}
Next i overrode the queryfortable function:
override func queryForTable() -> PFQuery! {
let query = PFQuery(className: "User")
if let queryLoc = currLocation {
query.whereKey("location", nearGeoPoint: PFGeoPoint(latitude: queryLoc.latitude, longitude: queryLoc.longitude), withinMiles: 50)
query.limit = 40
query.orderByAscending("createdAt")
println("\(queryLoc.latitude)")
return query
} else {
query.whereKey("location", nearGeoPoint: PFGeoPoint(latitude: 37.411822, longitude: -121.941125), withinMiles: 50)
query.limit = 40
query.orderByAscending("createdAt")
println("else statement")
return query
}
}
then the objectAtIndexPath function
override func objectAtIndexPath(indexPath: NSIndexPath!) -> PFObject! {
var obj : PFObject? = nil
if indexPath.row < self.objects.count {
obj = self.objects[indexPath.row] as? PFObject
}
return obj
}
and lastly I returned the cell, but for some reason it does not work:
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!, object: PFObject?) -> PFTableViewCell! {
let cell = tableView.dequeueReusableCellWithIdentifier("CustomCell", forIndexPath: indexPath) as TableViewCell
cell.userName?.text = object?.valueForKey("FBName") as? String
let userProfilePhotoURLString = object?.valueForKey("pictureURL") as? String
var pictureURL: NSURL = NSURL(string: userProfilePhotoURLString!)!
var urlRequest: NSURLRequest = NSURLRequest(URL: pictureURL)
NSURLConnection.sendAsynchronousRequest(urlRequest, queue: NSOperationQueue.mainQueue()) { (NSURLResponse response, NSData data,NSError error) -> Void in
if error == nil && data != nil {
cell.userImage?.image = UIImage(data: data)
}
}
cell.ratingsView?.show(rating: 4.0, text: nil)
return cell
}
ps, i have the number of sections set to 1, just didnt think that method would be useful to show here.
okay I found the issue! The issue was that I was trying to use PFQuery in order to retrieve a list of PFUsers. I found out that cannot be done using PFQuery infact PFUser has it's own query method for retrieving information from its users.
all i had to do was replace this line:
let query = PFQuery(className: "User")
with this:
let query = PFUser.query()

Resources