How to download image from asynchronously in swift - ios

Hi I am developing a app using swift2.2 am getting a data from a server and am passing it to the collection view.am getting more images from the server i cant pass it very quickly it consumes so much of time so i need to to pass that quickly as much as possible.
code in my view controller:
func jsonParsingFromURL() {
self.view.makeToastActivity(.Center)
if Reachability.isConnectedToNetwork() == true {
Alamofire.request(.POST, "http://something.com=\(appDelCityname)&fromLimit=0&toLimit=20", parameters: nil, encoding: .URL, headers: nil).response {
(req, res, data, error) - > Void in
let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print(dataString)
let json = JSON(data: data!)
let jsonData = json["ad_count"].int
if jsonData == 0 {
let alert = UIAlertController(title: "sorry!", message: "No Ads availabe", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
} else {
self.startParsing(data!)
}
}
} else {
let alert = UIAlertController(title: "No Internet Connection", message: "make sure your device is connected to the internet", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
}
func startParsing(data: NSData) {
let json = JSON(data: data)
let mainArr = json["subcategory"].array!
for item in mainArr {
self.fetchImage = item["images"].stringValue
self.fetchPrice = item["originalprice"].stringValue
self.fetchTitle = item["adtitle"].stringValue
self.fetchCityname = item["districtname"].stringValue
let takefirstImg = self.fetchImage.componentsSeparatedByString(",")
let firstimgofStr = takefirstImg[0]
dispatch_async(dispatch_get_main_queue(), {
() - > Void in
let URL_API_HOST2: String = "https://www.something.com"
let url = NSURL(string: URL_API_HOST2 + firstimgofStr)
let data = NSData(contentsOfURL: url!)
let imageyy = UIImage(data: data!)
self.priceArr.append(self.fetchPrice)
self.cityArr.append(self.fetchCityname)
self.adtitleArr.append(self.fetchTitle)
print("something = \(firstimgofStr)")
print("check image = \(self.fetchTitle)")
self.imageDict.append(imageyy!)
self.view.hideToastActivity()
})
self.refresh()
}
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) - > Int {
return imageDict.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) - > UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("FilterCell", forIndexPath: indexPath) as!SecondTableViewCell
cell.FifTitle.text = adtitleArr[indexPath.item]
cell.FifAddress.text = cityArr[indexPath.item]
cell.Fifprice.text = priceArr[indexPath.item]
dispatch_async(dispatch_get_main_queue(), {
cell.Fifimage.image = self.imageDict[indexPath.item]
})
// cell.Fifimage.sd_setImageWithURL(NSURL(string: URL_API_HOST2 + (firstImage as String)))
return cell
}
func collectionView(collectionView: UICollectionView, layout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) - > CGSize {
return imageDict[indexPath.item].size
}
I am having the library of SDWebImage but which will allow only url type but i have to use UIImage value to calculate the size of image to get Pinterest style view.according to my method it works well but when i get more value from the server it makes very late to display so help me to work with this process am struggling from the morning.

Related

Add more data when tableview reached end

I am getting some data from server using Alamofire like this :
func getNewestFeed(order:String , page:Int) {
Alamofire.request("https://blahblah.com/api/front/\(page)/\(order)", method: .post, parameters: ["foo":"bar"], encoding: JSONEncoding.default, headers: nil).responseJSON(completionHandler: { respone in
if respone.response?.statusCode == 200 {
let result = respone.result.value as! [String:Any]
self.newestArray = result["records"] as! [Any]
self.tableView.reloadData()
} else {
//Show error
let alertController = UIAlertController(title: "Error", message: "", preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertController.addAction(cancelAction)
OperationQueue.main.addOperation { self.present(alertController, animated: true, completion: nil) }
}
})
}
by default server gives me page 1, now I need to add more data too self.newestArray to load more contents. So here is the code :
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let lastElement = newestArray.count - 1
if indexPath.row == lastElement {
//add more data
}
}
Now I am trying to add result to self.newestArray , like this :
let result = respone.result.value as! [String:Any]
self.newestArray.append(result["records"] as! [Any])
self.tableView.reloadData()
but crashes with this error :
Could not cast value of type 'Swift.Array' (0x109c3c828) to
'Swift.Dictionary' (0x109c3c798).
How should I addd more array to self.newestArray and show it again in table view ?
append(_:) is used to add a single element to the end of the array.
There is append(contentsOf:) if you want to add a collection of items:
self.newestArray.append(contentsOf: result["records"] as! [Any])

How to show first data in table view while fetch data from api

I have one collection view and it have some 5 cells. Which are I am fetching from api to show the cells data in collection view. And when user click any cell, that approprate data will display in below table view.
Now, every thing works fine. But when I load first time my view. No data are displaying in my table view... What I mean is? By default first data of collection view cell have to show in tableview. But I am not getting or not able to display.
If I click any cell only, I can see the data in my table view. But what I need is - By default first cell of collection view have to display in table view when ever i open that screen
How to do that?
Here is my code:
#IBOutlet var BTCollectionView: UICollectionView!
#IBOutlet var DLTableView: UITableView!
var BTdata = [BTData]()
var Dealsdata = [DealsData]()
override func viewDidLoad()
{
super.viewDidLoad()
// nib for custom cell (table view)
let nib = UINib(nibName:"DealsListTableCell", bundle: nil)
DLTableView.registerNib(nib, forCellReuseIdentifier: "DealCell")
ListBusinessTypes()
}
// Values from Api for Business Types
func ListBusinessTypes()
{
let token = NSUserDefaults.standardUserDefaults().valueForKey("access_token") as! String
let headers = ["x-access-token": token]
let request = NSMutableURLRequest(URL: NSURL(string: "httpsome url")!,
cachePolicy: .UseProtocolCachePolicy,
timeoutInterval: 10.0)
request.HTTPMethod = "GET"
request.allHTTPHeaderFields = headers
let session = NSURLSession.sharedSession()
let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
if (error != nil)
{
print(error)
let ErrorAlert = UIAlertController(title: "Error", message: "Problem with internet connectivity or server, please try after some time", preferredStyle: UIAlertControllerStyle.Alert)
// add an action (button)
ErrorAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
// show the alert
self.presentViewController(ErrorAlert, animated: true, completion: nil)
}
else
{
if let json = (try? NSJSONSerialization.JSONObjectWithData(data!, options: [])) as? Dictionary<String,AnyObject>
{
let success = json["success"] as? Int
if(success == 1)
{
if let typeValues = json["data"] as? [NSDictionary]
{
dispatch_async(dispatch_get_main_queue(),{
for item in typeValues
{
self.BTdata.append(BTData(json:item))
self.BTCollectionView.reloadData()
}
})
}
}
else
{
let message = json["message"] as? String
print(message)
let ServerAlert = UIAlertController(title: "Error", message: message, preferredStyle: UIAlertControllerStyle.Alert)
// add an action (button)
ServerAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
// show the alert
self.presentViewController(ServerAlert, animated: true, completion: nil)
}
}
}
})
dataTask.resume()
}
// Mark : Collection View Delegate and Datasource(Business Type)
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return BTdata.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
let cell: DDLCollectionCell = collectionView.dequeueReusableCellWithReuseIdentifier("HCollectionCell", forIndexPath: indexPath) as! DDLCollectionCell
cell.BTName.text = BTdata[indexPath.row].BTNames
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
{
ListDeals(BTdata[indexPath.row].BTIds!)
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
// number of rows
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return Dealsdata.count
}
// calling each cell based on tap and users ( premium / non premium )
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let tabcell = tableView.dequeueReusableCellWithIdentifier("DealCell") as! DealsListTableCell
tabcell.DealName.text = Dealsdata[indexPath.row].DealNames
if let imgURL = NSURL(string: Dealsdata[indexPath.row].DealImageUrls!)
{
let request: NSURLRequest = NSURLRequest(URL: imgURL)
let session = NSURLSession.sharedSession()
let Imgtask = session.dataTaskWithRequest(request)
{
(data, response, error) -> Void in
if (error == nil && data != nil)
{
func display_image()
{
tabcell.DealImage.image = UIImage(data: data!)
}
dispatch_async(dispatch_get_main_queue(), display_image)
}
}
Imgtask.resume()
}
else
{
tabcell.DealImage.image = UIImage(named: "FBLogo")
}
let formatter = NSDateFormatter()
formatter.locale = NSLocale(localeIdentifier: "en_US")
formatter.dateFormat = "yyyy-MM-dd'T'hh:mm:ss.SSSSxxx"
let date = formatter.dateFromString(Dealsdata[indexPath.row].DealExpiry!)
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .MediumStyle
dateFormatter.timeStyle = .NoStyle
dateFormatter.locale = NSLocale(localeIdentifier: "en_US")
let FormattedDate = dateFormatter.stringFromDate(date!)
tabcell.RegPriceLabel.text = String(Dealsdata[indexPath.row].DealRegularPrice!)
tabcell.SalePriceLabel.text = String(Dealsdata[indexPath.row].DealSalePrice!)
tabcell.DealExpiryDate.text = "Expiries on : "+FormattedDate
let BArrayValue:NSDictionary = Dealsdata[indexPath.row].DealBusinessDetails!
let BName = BArrayValue.valueForKey("business_name") as! String
let BImage = BArrayValue.valueForKey("images") as! NSArray
let BMainImage = BImage[0] as! NSDictionary
let FinalImage = BMainImage.valueForKey("url") as! String
if let imgURL2 = NSURL(string: FinalImage)
{
let request: NSURLRequest = NSURLRequest(URL: imgURL2)
let session = NSURLSession.sharedSession()
let Imgtask = session.dataTaskWithRequest(request)
{
(data, response, error) -> Void in
if (error == nil && data != nil)
{
func display_image()
{
tabcell.DealBusinessImage.image = UIImage(data: data!)
}
dispatch_async(dispatch_get_main_queue(), display_image)
}
}
Imgtask.resume()
}
else
{
tabcell.DealBusinessImage.image = UIImage(named: "FBLogo")
}
let BLatLng = Dealsdata[indexPath.row].DealCoordinates
let UserLocation = CLLocation(latitude: NewCurrentLatitude, longitude: NewCurrentLongitude)
let BusinessLocation = CLLocation(latitude: BLatLng![0] as! Double, longitude: BLatLng![1] as! Double)
let distance = UserLocation.distanceFromLocation(BusinessLocation) / 1000
tabcell.DealBusinessNameWithDistance.text = BName+" - "+String(format: "%.1f",distance)+" Km"
return tabcell
}
Please help me out. Thanks!
Does i need to change any thing in below line:
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
{
ListDeals(BTdata[indexPath.row].BTIds!)
}
Try to call ListDeals(BTdata[0].BTIds!) after you loaded the data from your API.
...
if let typeValues = json["data"] as? [NSDictionary]
{
dispatch_async(dispatch_get_main_queue(),{
for item in typeValues
{
self.BTdata.append(BTData(json:item))
self.BTCollectionView.reloadData()
}
ListDeals(BTdata[0].BTIds!)
})
}
...

How to use closures to return a JSON value from a NSURLSession

I am trying to return a result from a JSON object but unable to do so. I am new to Swift so kindly explain me how to do so. In the below code I want to return json_level_number in the return of function fetchNumberOfSections () where i have hard coded as 5 right now return 5. If i declare a variable json_level_number just above the reachability code it sort of solves the problem but then it is returning '0' for the first time. The API returns 2 each time.
Code as below:
func fetchNumberOfSections () -> Int {
if Reachability.isConnectedToNetwork() == true {
// Below code to fetch number of sections
var urlAsString = "http://themostplayed.com/rest/fetch_challenge_sections.php"
urlAsString = urlAsString+"?apiKey="+apiKey
print (urlAsString)
let url = NSURL(string: urlAsString)!
let urlSession = NSURLSession.sharedSession()
let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in
if (error != nil) {
print(error!.localizedDescription)
}
do {
let jsonResult = (try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)) as! NSDictionary
let json_level_number: String! = jsonResult["level_number"] as! String
//
dispatch_async(dispatch_get_main_queue(), {
// self.dateLabel.text = jsonDate
// self.timeLabel.text = jsonTime
print(json_level_number)
// self.activityIndicatorStop()
})
}
catch let errorJSON {
print (errorJSON)
// alert box code below
let alert = UIAlertController(title: "JSON Error!", message:"Error processing JSON.", preferredStyle: .Alert)
let action = UIAlertAction(title: "OK", style: .Default) { _ in
// Put here any code that you would like to execute when
self.dismissViewControllerAnimated(true, completion: {})
}
alert.addAction(action)
self.presentViewController(alert, animated: true, completion: nil)
// alert box code end
}
})
jsonQuery.resume()
// End
}
else {
print("Internet connection FAILED")
self.performSegueWithIdentifier("nointernet", sender: nil)
}
return 5
}

iOS Keep url array order when saving images into an array

I'm trying to do the following.
I have an array that contains several URLs for different images. These images will be displayed into a scrollview and I want to keep this order to be able to delete specific images at a specific index.
Right now I'm using a for loop, first I load the array with NSNull objects and afterward I run the loop replacing all the objects with images. This doesn't seem to be really efficient, specially when the app loads from the background.
This is my code:
func downloadImagesfromUrlArray(){
for var i=0;i < graphsURLlist.count; i++ {
if let data = NSData(contentsOfURL: graphsURLlist[i]){
let image = UIImage(data: data)
pageImages.replaceObjectAtIndex(i, withObject: image!)
//self.scaleImagesandScrollView()
}else{
NSLog("%#", i)
var alert = myAlertController(title: nil, message: "Error trying to update the charts. Try again later \(i)",
preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
//Enter queue for every image to download
}
dispatch_group_leave(self.group)
}
Is there a better approach to do this?
Thanks
You better want to download images asynchronously and cache them. Before the images are downloaded it's better to display spinner, and then replace it with an image.
Here are a few related methods from my latest app:
func downloadAndCacheImg(url: String?, cell: AppCell, tableView: UITableView, indexPath: NSIndexPath) {
if url == nil { return }
let charactersToRemove = NSCharacterSet.alphanumericCharacterSet().invertedSet
let cacheFilename = "".join(url!.componentsSeparatedByCharactersInSet(charactersToRemove))
if let fullFilename = prefixFilenameWithDirectory(cacheFilename), img = UIImage(named: fullFilename) {
cell.setAppImage(img)
return
}
if let nsUrl = NSURL(string: url!) {
NSURLConnection.sendAsynchronousRequest(NSURLRequest(URL: nsUrl), queue: NSOperationQueue.mainQueue(), completionHandler: { (response, data, error) -> Void in
if let data = data, img = UIImage(data: data) {
if let fullFilename = self.prefixFilenameWithDirectory(cacheFilename) {
data.writeToFile(fullFilename, atomically: true)
}
if let cell = tableView.cellForRowAtIndexPath(indexPath) as? AppCell {
cell.setAppImage(img)
}
}
})
}
}
func prefixFilenameWithDirectory(filename: String) -> String? {
var dir = NSFileManager.defaultManager().URLForDirectory(.CachesDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true, error: nil)
dir = dir?.URLByAppendingPathComponent(filename)
return dir?.path
}

UITableViewCell were narrowed when first load

When the cells first appear,they will look like my picture shows.If scroll top then scroll down let them show again,they will be normal.The top three cells is always being normal while the bottom are narrowed.This is my code`
import UIKit
class AllCommentsViewController: UIViewController {
#IBAction func unwindToAllComments(sender: UIStoryboardSegue){
if sender.identifier == "unwindToAllComments"{
}
}
override func awakeFromNib() {
let photo = ZLLPhoto(withoutDataWithObjectId: "55cd717700b0875fb6cc125f")
photo.fetch()
self.photo = photo
}
var photo: ZLLPhoto!
var comments = [ZLLComment]()
#IBAction func commentButtonClicked(sender: UIButton){
performSegueWithIdentifier("comment", sender: nil)
}
private func initialCommentsQuery() -> AVQuery {
let query = ZLLComment.query()
query.whereKey("photo", equalTo: photo)
query.limit = 20
query.orderByDescending("likeCount")
query.addDescendingOrder("createdAt")
query.includeKey("score")
query.includeKey("author")
return query
}
func getFirst(){
initialCommentsQuery().findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if error == nil {
if objects.count != 0 {
let comments = objects as! [ZLLComment]
self.comments = comments
var indexPaths = [NSIndexPath]()
for i in 0..<objects.count{
var indexPath = NSIndexPath(forRow: i, inSection: 2)
indexPaths.append(indexPath)
}
self.tableView.beginUpdates()
self.tableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: .None)
self.tableView.endUpdates()
self.tableView.footer.endRefreshing()
self.tableView.footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: "loadMore")
self.tableView.header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: "refresh")
}
}else{
print(error)
}
self.tableView.footer.endRefreshing()
}
}
func loadMore(){
let last = comments.last!
let query = initialCommentsQuery()
query.whereKey("likeCount", lessThanOrEqualTo: last.likeCount)
query.whereKey("createdAt", lessThan: last.createdAt)
query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if error == nil {
if objects.count != 0{
var indexPaths = [NSIndexPath]()
for i in 0..<objects.count{
let indexPath = NSIndexPath(forRow: self.comments.count + i, inSection: 2)
indexPaths.append(indexPath)
}
let comments = objects as! [ZLLComment]
self.comments.extend(comments)
self.tableView.beginUpdates()
self.tableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: .None)
self.tableView.endUpdates()
}
}else{
print(error)
}
self.tableView.footer.endRefreshing()
}
}
func refresh(){
let first = comments.first!
let query = initialCommentsQuery()
query.whereKey("likeCount", greaterThanOrEqualTo: first.likeCount)
query.whereKey("createdAt", greaterThan: first.createdAt)
query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if error == nil {
if objects.count != 0 {
var comments = objects as! [ZLLComment]
comments.extend(self.comments)
self.comments = comments
var indexPaths = [NSIndexPath]()
for i in 0..<objects.count{
var indexPath = NSIndexPath(forRow: i, inSection: 2)
indexPaths.append(indexPath)
}
self.tableView.beginUpdates()
self.tableView.insertRowsAtIndexPaths(indexPaths,
withRowAnimation: UITableViewRowAnimation.None)
self.tableView.endUpdates()
}
}else{
print(error)
}
self.tableView.header.endRefreshing()
}
}
#IBOutlet weak var commentButton: UIButton!
#IBOutlet weak var photoTitle: UILabel!{
didSet{
photoTitle.text = photo.title
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "comment" {
let VC = segue.destinationViewController as! CommentPhotoViewController
VC.photo = photo
}else if segue.identifier == "showUser"{
let VC = segue.destinationViewController as! UserInfoTableViewController
VC.user = sender as! ZLLUser
}
}
#IBAction func likeButtonClicked(sender: UIButton) {
let indexPath = tableView.indexPathForCellContainingView(sender)!
let comment = comments[indexPath.row]
let I = ZLLUser.currentUser()
let cell = tableView.cellForRowAtIndexPath(indexPath) as! CommentCell
if !cell.liked{
I.likeComment(comment, completion: { (error) -> Void in
if error == nil {
comment.incrementKey("likeCount")
cell.likeCount += 1
cell.liked = true
}else{
print(error)
}
})
}else{
I.unlikeComment(comment, completion: { (error) -> Void in
if error == nil{
comment.incrementKey("likeCount", byAmount: -1)
cell.likeCount -= 1
cell.liked = false
}else{
print(error)
}
})
}
}
//XIBload
#IBOutlet weak var tableView: UITableView!
#IBOutlet var titleScoreLabel: UILabel?
#IBOutlet var titleLabel: UILabel?
#IBOutlet var photoCell: UITableViewCell!
override func viewDidLoad() {
NSBundle.mainBundle().loadNibNamed("PhotoCell", owner: self, options: nil)
tableView.footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: "getFirst")
let query = ZLLScore.query()
query.whereKey("photo", equalTo: photo)
query.whereKey("scorer", equalTo: ZLLUser.currentUser())
query.countObjectsInBackgroundWithBlock { (count, error) -> Void in
if error == nil {
if count > 0{
self.commentButton.setImage(UIImage(named: "comments_add_comment")!, forState: UIControlState.Normal)
}
}else{
print(error)
}
}
}
}
extension AllCommentsViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 44
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 3
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
switch indexPath.section {
case 0:
let cell = tableView.dequeueReusableCellWithIdentifier("photoCell") as! PhotoCell
cell.loadPhoto2(photo)
return cell
case 1:
tableView
let cell = tableView.dequeueReusableCellWithIdentifier("commentCell", forIndexPath: indexPath) as! CommentCell
cell.loadPhotoInfo(photo)
return cell
default:
let cell = tableView.dequeueReusableCellWithIdentifier("commentCell", forIndexPath: indexPath) as! CommentCell
if indexPath.row == 0{
cell.smallTagImage.image = UIImage(named: "jian")
return cell
}
cell.delegate = self
cell.loadComment(comments[indexPath.row])
return cell
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section{
case 2:
return comments.count
default:
return 1
}
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 1
}
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
switch section{
case 0:
return 1
default:
return 10
}
}
}
extension AllCommentsViewController: PhotoCellDelegate{
func photoCellDidTapUserField(photoCell: PhotoCell) {
}
func photoCellDidClickShareButton(photoCell: PhotoCell) {
//
let indexPath = tableView.indexPathForCell(photoCell)!
let share = UIAlertController(title: "分享图片", message: "\(photo.title)", preferredStyle: UIAlertControllerStyle.ActionSheet)
let weibo = UIAlertAction(title: "微博", style: UIAlertActionStyle.Default) { (action) -> Void in
if !WeiboSDK.isWeiboAppInstalled(){
ZLLViewModel.showHintWithTitle("未安装微博应用", on: self.view)
return
}
if !ShareSDK.hasAuthorizedWithType(ShareTypeSinaWeibo){
let authorize = UIAlertController(title: "未获取授权", message: "是否要获取授权", preferredStyle: UIAlertControllerStyle.Alert)
let confirm = UIAlertAction(title: "确认", style: UIAlertActionStyle.Default, handler: { (action) -> Void in
ShareSDK.getUserInfoWithType(ShareTypeSinaWeibo, authOptions: nil, result: { (result, userInfo, errorInfo) -> Void in
if !result {
ZLLViewModel.showHintWithTitle("授权失败!", on: self.view)
return
}
let image = ShareSDK.imageWithData(self.photo.imageFile.getData(), fileName: "test1", mimeType: "")
let content = ShareSDK.content("a", defaultContent: "b", image: image, title: "c", url: "", description: "d", mediaType: SSPublishContentMediaTypeImage)
ShareSDK.clientShareContent(content, type: ShareTypeSinaWeibo, statusBarTips: true, result: { (type, state, shareInfo, errorInfo, end) -> Void in
})
})
})
let cancel = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
authorize.addAction(confirm)
authorize.addAction(cancel)
self.presentViewController(authorize, animated: true, completion: nil)
return
}
let image = ShareSDK.imageWithData(self.photo.imageFile.getData(), fileName: "test1", mimeType: "")
let content = ShareSDK.content("a", defaultContent: "b", image: image, title: "c", url: "", description: "d", mediaType: SSPublishContentMediaTypeImage)
ShareSDK.clientShareContent(content, type: ShareTypeSinaWeibo, statusBarTips: true, result: { (type, state, shareInfo, errorInfo, end) -> Void in
})
}
let qZone = UIAlertAction(title: "qq空间", style: UIAlertActionStyle.Default) { (action) -> Void in
//
if !QQApiInterface.isQQInstalled(){
ZLLViewModel.showHintWithTitle("未安装腾讯QQ", on: self.view)
return
}
if !ShareSDK.hasAuthorizedWithType(ShareTypeQQSpace){
let authorize = UIAlertController(title: "未获取授权", message: "是否要获取授权", preferredStyle: UIAlertControllerStyle.Alert)
let confirm = UIAlertAction(title: "确认", style: UIAlertActionStyle.Default, handler: { (action) -> Void in
ShareSDK.getUserInfoWithType(ShareTypeQQSpace, authOptions: nil, result: { (result, userInfo, errorInfo) -> Void in
if !result {
ZLLViewModel.showHintWithTitle("授权失败!", on: self.view)
return
}
let image = ShareSDK.imageWithData(self.photo.imageFile.getData(), fileName: "test1", mimeType: "")
let content = ShareSDK.content("a", defaultContent: "b", image: image, title: "c", url: "", description: "d", mediaType: SSPublishContentMediaTypeImage)
ShareSDK.clientShareContent(content, type: ShareTypeQQSpace, statusBarTips: true, result: { (type, state, shareInfo, errorInfo, end) -> Void in
})
})
})
let cancel = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
authorize.addAction(confirm)
authorize.addAction(cancel)
self.presentViewController(authorize, animated: true, completion: nil)
return
}
let image = UIImage(data: self.photo.imageFile.getData())
let data = UIImageJPEGRepresentation(image, 0.1)
let attachment = ShareSDK.imageWithData(data, fileName: "test1", mimeType: "")
let content = ShareSDK.content("a", defaultContent: "b", image: attachment, title: "c", url: "www.baidu.com", description: "d", mediaType: SSPublishContentMediaTypeImage)
ShareSDK.clientShareContent(content, type: ShareTypeQQSpace, statusBarTips: true, result: { (type, state, shareInfo, errorInfo, end) -> Void in
})
}
let weixin = UIAlertAction(title: "微信好友", style: UIAlertActionStyle.Default) { (action) -> Void in
if !QQApiInterface.isQQInstalled(){
ZLLViewModel.showHintWithTitle("未安装腾讯QQ", on: self.view)
return
}
if !ShareSDK.hasAuthorizedWithType(ShareTypeQQSpace){
let authorize = UIAlertController(title: "未获取授权", message: "是否要获取授权", preferredStyle: UIAlertControllerStyle.Alert)
let confirm = UIAlertAction(title: "确认", style: UIAlertActionStyle.Default, handler: { (action) -> Void in
ShareSDK.getUserInfoWithType(ShareTypeQQ, authOptions: nil, result: { (result, userInfo, errorInfo) -> Void in
if !result {
ZLLViewModel.showHintWithTitle("授权失败!", on: self.view)
return
}
let image = ShareSDK.imageWithData(self.photo.imageFile.getData(), fileName: "test1", mimeType: "")
let content = ShareSDK.content("a", defaultContent: "b", image: image, title: "c", url: "", description: "d", mediaType: SSPublishContentMediaTypeImage)
ShareSDK.clientShareContent(content, type: ShareTypeQQ, statusBarTips: true, result: { (type, state, shareInfo, errorInfo, end) -> Void in
})
})
})
let cancel = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
authorize.addAction(confirm)
authorize.addAction(cancel)
self.presentViewController(authorize, animated: true, completion: nil)
return
}
let image = ShareSDK.imageWithData(self.photo.imageFile.getData(), fileName: "test1", mimeType: "")
let content = ShareSDK.content("a", defaultContent: "b", image: image, title: "c", url: "", description: "d", mediaType: SSPublishContentMediaTypeImage)
ShareSDK.clientShareContent(content, type: ShareTypeQQ, statusBarTips: true, result: { (type, state, shareInfo, errorInfo, end) -> Void in
})
}
let pengyouquan = UIAlertAction(title: "朋友圈", style: UIAlertActionStyle.Default) { (action) -> Void in
}
let cancl = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
share.addAction(weibo)
share.addAction(qZone)
share.addAction(weixin)
share.addAction(pengyouquan)
share.addAction(cancl)
self.presentViewController(share, animated: true, completion: nil)
}
func photoCellDidClickMoreButton(photoCell: PhotoCell) {
let indexPath = tableView.indexPathForCell(photoCell)!
let alertController = UIAlertController(title: "更多", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
let report = UIAlertAction(title: "举报", style: UIAlertActionStyle.Default) { (alertAction) -> Void in
let confirmReport = UIAlertController(title: "确认举报?", message: nil, preferredStyle: UIAlertControllerStyle.Alert)
let delete = UIAlertAction(title: "确认", style: UIAlertActionStyle.Destructive) { (alertAction) -> Void in
let report = ZLLReport.new()
report.reportedPhoto = self.photo
report.reporter = ZLLUser.currentUser()
let success = report.save()
if success{
ZLLViewModel.showHintWithTitle("举报成功", on: self.view)
}else{
ZLLViewModel.showHintWithTitle("举报失败", on: self.view)
}
}
let cancel = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
confirmReport.addAction(delete)
confirmReport.addAction(cancel)
self.presentViewController(confirmReport, animated: true, completion: nil)
}
alertController.addAction(report)
if photo.owner.objectId == ZLLUser.currentUser().objectId{
let delete = UIAlertAction(title: "删除图片", style: UIAlertActionStyle.Destructive) { (alertAction) -> Void in
let confirmDelete = UIAlertController(title: "确认删除?", message: nil, preferredStyle: UIAlertControllerStyle.Alert)
let delete = UIAlertAction(title: "确认", style: UIAlertActionStyle.Destructive) { (alertAction) -> Void in
let success = self.photo.delete()
self.photo.deleteInBackgroundWithBlock({ (success, error) -> Void in
if success{
self.performSegueWithIdentifier("deleteComplete", sender: nil)
ZLLViewModel.showHintWithTitle("删除成功", on: self.view)
self.myPopBackButtonClicked(nil)
}else{
print(error)
}
})
}
let cancel = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
confirmDelete.addAction(delete)
confirmDelete.addAction(cancel)
self.presentViewController(confirmDelete, animated: true, completion: nil)
}
alertController.addAction(delete)
}
let cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
}
extension AllCommentsViewController: CommentCellProtocol{
func commentCellDidTapAuthorLabel(cell: CommentCell) {
let indexPath = tableView.indexPathForCell(cell)!
let comment = comments[indexPath.row]
let user = comment.author
performSegueWithIdentifier("showUser", sender: user)
}
}`
In Your PhotoCell class, add this snippet code.
override func didMoveToSuperview() {
layoutIfNeeded()
}
Your problem is in the section where you define your tableView.
In your tableView extension, you set the numberOfSectionsInTableView method to return 3 rows, so your code defining the cell dimensions only runs on the first 3 rows.
Try setting your numberOfSections method to the number of rows you want based on the dimensions of your view, it looks to be about 5.

Resources