NSUserDefaults Not Saving TextField Text (Swift) - cocoa-touch

I'm trying to create a game with Swift, and I want to add the ability to create a username, which will be saved in NSUserDefaults. This is my code:
println("Textfield Text: \(usernameTextfield.text)")
NSUserDefaults.standardUserDefaults().setObject(usernameTextfield.text, forKey:"Username")
NSUserDefaults.standardUserDefaults().synchronize()
println(NSUserDefaults.standardUserDefaults().objectForKey("Username") as? String)
The output is:
Textfield Text: MyUsername
nil
The only explanation I can see as to why it is printing nil is that either the saving or the loading of the username is failing. Is there any way this can be corrected or am I doing something wrong?
Any help is appreciated!

println("Textfield Text: \(usernameTextfield.text)")
var myValue:NSString = usernameTextfield.text
NSUserDefaults.standardUserDefaults().setObject(myValue, forKey:"Username")
NSUserDefaults.standardUserDefaults().synchronize()
var myOutput: AnyObject? = NSUserDefaults.standardUserDefaults().objectForKey("Username")
println(myOutput)

In Swift 4.1
UserDefaults.standard.set(textfield.text, forKey: "yourKey") // saves text field text
UserDefaults.standard.synchronize()
// To Retrieve
textfield.text = UserDefaults.standard.value(forKey:"yourKey") as? String

I made a small modification to Roman's answer with Swift 2.0 and Xcode 6.4.
saving:
var myValue:NSString = usernameTF.text
NSUserDefaults.standardUserDefaults().setObject(myValue, forKey:"Username")
NSUserDefaults.standardUserDefaults().synchronize()
retrieving:
var myOutput = NSUserDefaults.standardUserDefaults().objectForKey("Username")
if (myOutput != nil)
{
self.title = "Welcome "+((myOutput) as! String)
}

In Swift 3.0
let userDefult = UserDefaults.standard //returns shared defaults object.
if let userName = usernameTextfield.text {
//storing string in UserDefaults
userDefult.set(userName, forKey: "userName") //Sets the value of the specified default key in the standard application domain.
}
print(userDefult.string(forKey: "userName")!)//Returns the string associated with the specified key.

For swift 3.0, You can create user default by,
UserDefaults.standard.set("yourValue", forKey: "YourString")
To Print the value in console :
print(UserDefaults.standard.string(forKey: "YourString")!)

Related

Searching PDF using PDFKIT in Swift

I am extremely new to swift so bear with me. I am trying to figure out how to search the PDF document for a particular string. I am assuming I need to use the findString function. I just do not know exactly how the parameters should be implemented. I am using Apple Docs. and couldn't see a description of this.
Thanks!=]
private func loadPDF(){
guard
let url = Bundle.main.url(forResource: pdfTitle, withExtension: "pdf"),
let document = PDFDocument(url:url)
else {fatalError()}
pdfView.document = document
}
func findString(_ string: String,
withOptions options: NSString.CompareOptions = []) -> [PDFSelection]
To get a list of matches you do something like this:
let matches = document.findString("foo", withOptions: .caseInsensitive)

Passing a tabelview indexPath.row as String to VC WebView

I have a TableViewController which I am attempting to pass through a URL to a WebView on another ViewController
I am overriding the below function, which works find if I make the URL static as you can see in the comment out let newsLink constant
let newsLink = "http://www.stuff.co.nz/business/industries/69108799/Kirkcaldie-Stains-department-store-to-become-David-Jones"
However with the below pulling the URL from indexPath.row it fails for some reason and passes through a nil value
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
let newsLink = (posts.objectAtIndex(indexPath.row).valueForKey("link") as! String)
//let newsLink = "http://www.stuff.co.nz/business/industries/69108799/Kirkcaldie-Stains-department-store-to-become-David-Jones"
println(newsLink)
let newsWebViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("idNewsWebViewController") as! NewsWebViewController
newsWebViewController.newsURL = NSURL(string: newsLink)
showDetailViewController(newsWebViewController, sender: self)
}
If I println() the below, I get exactly the same output as the URL I ahve hardcoded in the test let newsLink constant
println(posts.objectAtIndex(indexPath.row).valueForKey("link") as! String)
I can't figure out why this is failing. Hopefully someone smarter than me can help.
The code on the receiving end VC is below"
var newsURL : NSURL!
//var newsURL = NSURL(string: "http://www.google.co.nz")
#IBOutlet weak var newsWebView: UIWebView!
#IBOutlet weak var descTextView: UITextView!
and in the viewDidAppear function
let request : NSURLRequest = NSURLRequest(URL: newsURL!)
newsWebView.loadRequest(request)
More Info
var types
var posts = NSMutableArray()
var elements = NSMutableDictionary()
how I am adding objects
elements.setObject(urlLink, forKey: "link")
posts.addObject(elements)
Could you show the declaration / structure of the "posts" variable?
Without more information, the only thing I can think of is that the value of "link" is not actually a String, but something (maybe a NSURL) that when printed shows that content. That would explain the println showing the same url but the cast failing.
When you print, or implicitly convert any object to a String (as in the println), it calls the "description" method of that object.
For example:
class MyURLContainer {
var link:String
override func description() -> String {
return link
}
}
let url = MyURLContainer()
let url.link = "http://www.example.com"
println( "my link: \(url)" ) // this would show the link correctly
let link = url as? String // this will be nil, as url can't be casted to String
I think (posts.objectAtIndex(indexPath.row).valueForKey("link") does not return a String type. It might already be a NSURL, and hence showing you correct value in println()
Could you post some more details about it. Hope this helped.
It turns out it was the encoding on the URL that NSURL didn't like.
The solution was to use the below:
var escapedString = originalString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
I'm new to swift, but this seems a bit messy.

Core Data - Get managed object by URI

I'm trying to fetch managed objects from Core Data by their URI. For this I found an Objective-C example of a method (http://www.cocoawithlove.com/2008/08/safely-fetching-nsmanagedobject-by-uri.html) and converted it to Swift ...
func getManagedObjectWithURI(uri:NSURL) -> NSManagedObject?
{
if let psc = persistentStoreCoordinator
{
let objID = psc.managedObjectIDForURIRepresentation(uri);
if (objID != nil)
{
let obj:NSManagedObject = managedObjectContext!.objectWithID(objID!);
if (!obj.fault)
{
return obj;
}
let prd = NSComparisonPredicate(leftExpression: .expressionForEvaluatedObject(), rightExpression: NSExpression(forConstantValue: obj), modifier: .DirectPredicateModifier, type: .EqualToPredicateOperatorType, options: .allZeros);
let req = NSFetchRequest();
req.entity = objID?.entity;
req.predicate = prd;
var results:[NSManagedObject] = managedObjectContext!.executeFetchRequest(req, error: nil) as! [NSManagedObject];
if (!results.isEmpty)
{
return results.first;
}
}
}
return nil;
}
However the method always returns nil, i.e. the fetch request returns empty-handed and I don't know why. Up to the NSFetchRequest everything looks valid. Does anyone has an idea what could be wrong?
Check that the entity and the predicate contain the expected values.
Another suggestion is to write your predicate with NSPredicate(format:) for clarity.
request.predicate = NSPredicate(format: "self = %#", object)
I have changed your variable names for readability.
Solved the issue. It was actually related to another, deeper problem in my core data code explained here: Mac OSX - Core data isn't stored
The above method works fine otherwise.

Download font .ttf file from web and store on iPhone

Is it possible to download .ttf file from web and store it on iPhone. Then use that for for labels and all other stuff ? Because my client want to control fonts from database and don't want to just drop fonts to xcode project right away.
So in future if he wants to change font, he will add new font to database, app will recognize new font on web (thats already done with images, not a problem), download it and use as font.
Thanks.
Actually it is possible to dynamically add fonts to the iOS runtime like this:
NSData *fontData = /* your font-file data */;
CFErrorRef error;
CGDataProviderRef provider = CGDataProviderCreateWithCFData((CFDataRef)inData);
CGFontRef font = CGFontCreateWithDataProvider(provider);
if (! CTFontManagerRegisterGraphicsFont(font, &error)) {
CFStringRef errorDescription = CFErrorCopyDescription(error)
NSLog(#"Failed to load font: %#", errorDescription);
CFRelease(errorDescription);
}
CFRelease(font);
CFRelease(provider);
Source: This Blog Article of Marco Arment.
It is possible. I created an example swift project in github. You have to just add the few line below.
var uiFont : UIFont?
let fontData = data
let dataProvider = CGDataProviderCreateWithCFData(fontData)
let cgFont = CGFontCreateWithDataProvider(dataProvider)
var error: Unmanaged<CFError>?
if !CTFontManagerRegisterGraphicsFont(cgFont, &error)
{
print("Error loading Font!")
} else {
let fontName = CGFontCopyPostScriptName(cgFont)
uiFont = UIFont(name: String(fontName) , size: 30)
}
Github project link
The fonts have to be set in the plist of your app, and that file cannot be changed during runtime, so you need to compile your project with the fonts already added to it.
You'll have to think in other way of implementing it.
You could use FontLabel (https://github.com/vtns/FontLabel) or smth. similar to load ttfs from the file system. I don't think that you can use downloaded fonts with a UILabel. Because you need the plist entries for each font.
Swift 4 solution by extension:
extension UIFont {
/**
A convenient function to create a custom font with downloaded data.
- Parameter data: The local data from the font file.
- Parameter size: Desired size of the custom font.
- Returns: A custom font from the data. `nil` if failure.
*/
class func font(withData data: Data, size: CGFloat) -> UIFont? {
// Convert Data to NSData for convenient conversion.
let nsData = NSData(data: data)
// Convert to CFData and prepare data provider.
guard let cfData = CFDataCreate(kCFAllocatorDefault, nsData.bytes.assumingMemoryBound(to: UInt8.self), nsData.length),
let dataProvider = CGDataProvider(data: cfData),
let cgFont = CGFont(dataProvider) else {
print("Failed to convert data to CGFont.")
return nil
}
// Register the font and create UIFont.
var error: Unmanaged<CFError>?
CTFontManagerRegisterGraphicsFont(cgFont, &error)
if let fontName = cgFont.postScriptName,
let customFont = UIFont(name: String(fontName), size: size) {
return customFont
} else {
print("Error loading Font with error: \(String(describing: error))")
return nil
}
}
}
Usage:
let customFont = UIFont.font(withData: data, size: 15.0)

Where does the Finder obtain the "date added" of an item in a folder?

If a folder is placed in the Dock you can sort it by "date added" - this is usually the default for the Downloads folder. (Sometimes the Finder does not appear to be using the date added but the date modified, but it can find the date added.) Where is the Finder figuring this out from? The standard file metadata, i.e. as obtained by stat, getattrlist or FSGetCatInfo) does not contain it. TIA
Yep, the date added could be inferred from other structures. In fact, it resides in Spotlight metadata.
NSDate *dateAdded(NSURL *url)
{
NSDate *rslt = nil;
MDItemRef inspectedRef = nil;
inspectedRef = MDItemCreateWithURL(kCFAllocatorDefault, (CFURLRef)url);
if (inspectedRef){
CFTypeRef cfRslt = MDItemCopyAttribute(inspectedRef, (CFStringRef)#"kMDItemDateAdded");
if (cfRslt) {
rslt = (NSDate *)cfRslt;
}
}
return rslt;
}
Note: out of date now that Lion’s out.
The Finder isn’t, the Dock is. It tracks this data internally. If you remove a folder and put it back, the “date added” information is lost for existing items.
Here's a Swift 5.x version of Wojtek's answer:
public extension URL {
var dateAdded: Date? {
if let metadataItemValue = MDItemCreateWithURL(kCFAllocatorDefault, (self as CFURL)) {
return MDItemCopyAttribute(metadataItemValue, kMDItemDateAdded) as? Date
}
return nil
}
}
I've tested this back to Swift 4.x, and I think it'll compile without modification back to Swift 3.x if you need that too. Just be aware that, before Swift 5, its inferred visibility would be internal rather than public.