Swift not accepting text property? - function

I am using a UITableView and I am having some problems with the text property. I have declared everything properly and I am sure everything is correct. Here is my code with the error:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let cell : UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Test")
cell.text = taskAdder.tasks[indexPath.row].name
return cell
}
The error is on the line:
cell.text = taskAdder.tasks[indexPath.row].name
It says:
'text' is unavailable: APIs depreciated as of iOS 7 and earlier are unavailable in Swift.
I am unsure of what this error means or how to fix it.
Any Input and suggestions would be greatly appreciated.
Thanks in advance.

The error says there is no text method on "UITableViewCell"
Did you try "cell.textLabel", because textLabel, detailTextLabel are used to set text in UITableViewCell

cell.text is deprecated since iOS 7.
Use cell.textLabel.text
See for more info:
https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UITableViewCell_Class/index.html

Related

Why am I am getting an "Invalid (non-string) key in JSON dictionary" error message?

I am trying to use Swift to create a reference to an image and storing it in documents using a dictionary and JSON. I believe that I created the correct syntax for dictionary based on another SO answer that I found. The error message below happens when I press the button with function addButtonClicked. What am i doing wrong?
Error message:
Invalid (non-string) key in JSON dictionary
// Inside UICollectionViewCell
var representedAssetIdentifier: String? = nil
// Inside UIViewController
var count: Int = 0
var dictionary: [Int:String] = [:]
#objc func addButtonClicked() {
do {
let fileURL = try FileManager.default
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("example.json")
try JSONSerialization.data(withJSONObject: dictionary).write(to: fileURL)
} catch {
print("Error report: \(error.localizedDescription)")
}
let newViewController = PickerTest3()
self.navigationController?.pushViewController(newViewController, animated: true)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let cell = collectionView.cellForItem(at: indexPath) as? ImageCell {
let newCount = count
dictionary.updateValue(cell.representedAssetIdentifier!, forKey: newCount)
count += 1
selectedCells.append(indexPath)
cell.index = selectedCells.count
}
}
The error message is pretty clear. You can not create a JSON string using a dictionary that has integer keys. You need to use strings.
Note: Not related to your question but you should not write any file directly to the application support directory:
Use this directory to store all app data files except those associated with the user’s documents. For example, you might use this directory to store app-created data files, configuration files, templates, or other fixed or modifiable resources that are managed by the app. An app might use this directory to store a modifiable copy of resources contained initially in the app’s bundle. A game might use this directory to store new levels purchased by the user and downloaded from a server.
All content in this directory should be placed in a custom subdirectory whose name is that of your app’s bundle identifier or your company.
In iOS, the contents of this directory are backed up by iTunes and iCloud.
File System Basics

Expose indexPath to configureCell

Currently configureCell only has access to the cell and IndicatorInfo. In my use case, I would like to know the indexPath of the cell so that I know which cell I am configuring and customize accordingly. Specifically we want to very first cell (indexPath 0) to display slightly different from the rest of the cells.
IndicatorInfo is currently a struct, so I can't subclass it to add another field to store the indexPath.
Just change the definition of configureCell() and add indexPath to it as it is being called in collection view's cellForItemAt function :
collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
So basically, follow the steps below:
Go to file -> ButtonBarPagerTabStripViewCOntroller.swift
Look for configureCell() function.
Add indexPath: IndexPath as one of the arguments in the definition
Check for usage of configureCell() and pass the indexpath in the function call.
When you will start editing this file, it will ask you to unlock it. You will have to allow that in the prompt.
Now when you override your configureCell() function, it will give you the indexPath as well.
Refer the below screenshot:

NSAttributed string from html without hanging UI thread

I am trying to load some html text into an NSAttributedString and I am seeing the UI hang.
Looking around I am not sure if that is possible as its looks like it may have to run on the main thread: NSAttributedString from HTML in the background thread
In swift 3 iOS 10 I am able to run this without exception
let myString = // some html content
DispatchQueue.global(qos: .background).async {
let data = myString.data(using: .utf8)
let options: [String: Any] = [
NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue
]
do {
let attributedString = try NSAttributedString(data: data!, options: options, documentAttributes: nil)
DispatchQueue.main.async {
() -> Void in
self.label.attributedText = attributedString
}
} catch let error as NSError {
print(error.localizedDescription)
}
}
A couple things.
Not sure why it doesn't crash. But I suspect that its still running on the main thread as the UI still locks up for a few seconds.
There are images in the html. Wondering if that is was is causing most of the delay. I still want to display the images but wondering if I can pull them out and just display the text initially and load the images on a background thread. Not sure if there is anything built into NSAttributedString to pull out images, or doI have to parse them out manually.
Is there any way at all to get this data to load on a background thread so I can not lock up the UI when using an NSAttributedString initialized with html data?
Just came across the same situation, I just figure out setting value for "Timeout" key can reduce the Unresponding time.
var options = [NSAttributedString.DocumentReadingOptionKey : Any]()
options[.documentType] = NSAttributedString.DocumentType.html
options[.characterEncoding] = String.Encoding.utf8.rawValue
options[.timeout] = 5.0 //Important!You can adjust this value to suitable value.
I think the following line of code always runs in the main queue.There is no way to avoid UI hanging completely while using this function.
NSAttributedString(data: data!, options: options, documentAttributes: nil)

Extra argument 'error' in call? But I don't have an 'error' variable at all?

I don't have an error variable anywhere, is this a bug in Xcode? I'm very confused on what could be wrong. I've searched all of stack overflow for an answer on this, found nothing. I've tried for several hours to figure out why I'm getting this error for the line of func parseJson( data: NSData){
I'm a beginner who studies Swift day and night.
Here is my code below:
func parseJson( data: NSData){
do{
let json: AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: [])
if let unwrappedJson: AnyObject = json{
parseSongs(unwrappedJson)
}
}catch{
}
}
Clean the project and build
If that doesn't word
Restart xcode
Rewrite the code

How to populate UIImage in UITableViewCell using JSON containing data of a bytea field (PostgreSQL)?

I am populating an UITableView using data returned in JSON by a webservice with a PostgreSQL backend. The thumbnail image data is stored as bytea in the database.
The data returned by the JSON field 'thumbnail' (recentRiddims[indexPath.row].thumbnail) looks something like: \xffd8ffe000104a46494600010200000100010000ffdb0043000806060706050807070709 ...
One can tell it is a JPEG image by its magic byte 0xFFD8FF. However, the string appears to be escaped. In PHP I'm usually using pg_unescape_bytea(data) to get the actual image data which can be used to display images in browsers. Hence I've tried that with the same set of JSON data in PHP I know that the data is a valid JPEG image.
The app compiles and launches fine but the thumbnail UIImageView in the UITableViewCell displays empty (a grey box, color of the UIImageView's background), while the UILabels' texts are updated with data from JSON.
I'm new to Swift so I'm sure there's a simple way of getting this done that I do not know about yet.
the cellForRowAtIndexPath function looks like:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let recentRiddimsCell = tableView.dequeueReusableCellWithIdentifier("recentRiddimsCell", forIndexPath: indexPath) as! RecentRiddimsCell
// Configure the cell...
recentRiddimsCell.riddimLabel.text = recentRiddims[indexPath.row].riddim
recentRiddimsCell.labelLabel.text = recentRiddims[indexPath.row].label
//image test
var thumbnailString: String! = recentRiddims[indexPath.row].thumbnail
let imageData = NSData(data: thumbnailString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!)
let image = UIImage(data: imageData)
recentRiddimsCell.imageThumbnail.image = image
return recentRiddimsCell
}
recentRiddims is an array of tuples [(riddim: String, label: String, count: String, thumbnail: String)], containing the parsed JSON values for each key.
I assume the thumbnail does not show the image because the data is escaped.
Is there an equivalent of PHP's pg_unescape_bytea() or is the user supposed to unescape manually? (I'm not really sure how to manually unescape though.)
Is there an easier way of populating the UITableView via JSON data in swift?
The project's deployment target is set to iOS 8.4 using Universal, running latest XCode on Yosemite.
EDIT:
I no longer think the JSON data for key "thumbnail" is in escaped format, I just had a look into the database where the data is stored like \377\330\377\340\000\020JFIF\000\001\002\000\000\001\000 .... Apparently the conversion from \oct is done by the PHP webservice, though, I don't know why the thumbnail data begins with \x. I rather expected it to start with ffd8ff... or 0xffd8ff.... If the JSON data holds properly escaped bytea data, why does the app not show the thumbnail image at all?
After a good night of sleep that removed my brain-stall I instantly realized my mistake by looking at the code with a fresh mind; the data is valid image data encoded in hex, prepended by \x.
All I had to do was removing \x from the String object, using (thumbnailString as NSString).substringFromIndex(2) and then NSData.fromHexString(thumbnailString), to decode the hex string and create a NSData object from it.
The extension for NSData can be found here, credits go to Sjors Provoost.