Swift 3 Timer
I had to add a timer to an app recently. Here is the code I used:
Code
Stranger Things

PR's Tumblrdome
almost home

Kiana Khansmith
Sweet Seals For You, Always
$LAYYYTER

izzy's playlists!
Monterey Bay Aquarium

No title available

⁂

Discoholic 🪩
hello vonnie
I'd rather be in outer space 🛸
2025 on Tumblr: Trends That Defined the Year

JVL
cherry valley forever
Misplaced Lens Cap
Show & Tell
art blog(derogatory)
Three Goblin Art

seen from Malaysia

seen from United States

seen from United Kingdom

seen from Italy

seen from Canada
seen from Mexico
seen from Bolivia

seen from Malaysia
seen from United States

seen from United States

seen from United States
seen from United States

seen from United States
seen from United States
seen from United States
seen from United States
seen from United States
seen from United States
seen from United States

seen from United States
@devmobileapp
Swift 3 Timer
I had to add a timer to an app recently. Here is the code I used:
Code
Starbucks Takes Its Pioneering Mobile-Phone App to Grande Level
Starbucks Corp., a pioneer in getting consumers to pay for products with a mobile phone, is boosting spending on digital ventures this year as it enhances the capability of its app in Asia, Europe and Latin America.
I have been using the Starbucks app for a few years and I find it very convenient. It is more than an app. It is part of an entire infrastructure. In my mind, thinking about it as an app misses the big picture.
The coffee chain is promoting a new feature, introduced last year nationwide at U.S. stores, that lets customers order and pay for beverages in advance and pick them up without waiting in the cashier line. It plans to bring the Mobile Order & Pay program to China and Japan in 2016. Starbucks is also testing delivery through the app this year in the U.S., where it will roll out features such as personalized food recommendations.
BloomBerg News
Blackberry to stop making its own phones
Once-dominant smartphone maker Blackberry Ltd. said it will stop developing its phones in-house and shift that work to outside companies so it can focus on software manufacturing.
In a regulatory filing Wednesday, the Canadian company said it plans to “end all internal hardware development” on its Blackberry brand phones and “outsource that function to partners.”
“This allows us to reduce capital requirements and enhance return on invested capital,” Chief Executive John Chen said in the filing.
Blackberry will focus on developing “state-of-the-art security and device software,” Chen said in a call with investors Wednesday morning.
http://www.latimes.com/business/la-fi-tn-blackberry-phones-20160928-snap-story.html
Things Programmers Shout #544
“WHY THE F*CK DOES THIS NOT WORK?” … Hours Later… “I’M SUCH AN IDIOT…”
// submitted by anonymous
Oh look, it’s every problem I’ve ever had while coding!
Installing Apps on iPhone
Every time I install an app on iPhone, I have to type in my apple password. This is so tedious and unnecessary. I can understand needing this for paid apps and apps with in-app purchases. But I don’t understand this for free apps. At most, it should just be a confirmation and go.
In the screen above, I turned on Touch ID. This lets me use my fingerprint instead of typing in my password. However, this isn’t the default. I had to go find this option and turn it on. And most iPhone users don’t even know that this is possible.
This is a significant hurdle for businesses that want to use mobile apps. Getting someone to download and try an app is difficult enough. Once they get asked for their password and don’t remember it, the opportunity is lost.
Apple App Store Review Times
June 13 2016 - App Store review times are now much shorter. These changes are already in place, and have been widely noted in recent weeks. Apple is today confirming they’re not a fluke — they’re the result of systemic changes to how App Store review works.
Swift Dictionary Extension to Create HTTP Args
protocol ArgType {} extension String: ArgType {} extension Dictionary where Key: ArgType, Value: ArgType { func toHttpArgString() -> String { var r = String() for (n, v) in self { if !r.isEmpty { r += "&" } r += "\(n)=\(v)" } return r } }
let k = ["username" : "me", "password" : "secret"] k.toHttpArgString() Produces this: "password=secret&username=me"
Discussion
The protocol is needed so that I can restrict the dictionary to only [String: String]. Notice that the extension to the dictionary uses the where clause. An extension for generics, like Dictionary, can’t include actual types. What i wanted was String, but Swift won’t let me do that. So I made a prototype and then extended String so that it had that prototype. Then I made the Dictionary key and value type conform to the protocol. It is an indirect way to make that association, but that is all we have at this point.
Removing characters from a string in Swift
Here is an extension to remove characters from a string
extension String { // Modifies string in place mutating func removeCharsInCharacterSet(charSet: NSCharacterSet) { if let range = self.rangeOfCharacterFromSet(charSet, options: .LiteralSearch, range: nil) { self.replaceRange(range, with: "") } } // Creates a new string without modifying existing string func stringByRemovingCharactersInCharacterSet(charSet: NSCharacterSet) -> String { var newStr = self newStr.removeCharsInCharacterSet(charSet) return newStr } }
There are 2 functions. One of them modifies the string and the other returns a new string without modifying the existing one. These functions assume that there is already a character set that defines what characters to remove.
Multi Stopwatch
Multi Stopwatch
Some time ago, I had a need for a special stopwatch. I volunteered to be on the board for the city soccer league for kids. One of the main things we had to do was be personally present at the games to make sure things didn’t get out of control. It is surprising how people behave when 10 year olds are playing a game.
I always wanted to time the games to make sure that the referees were running the correct amount of time so a stopwatch was a natural solution. There were two challenges. We often monitored more than one game at a time and we did not always get there on time.
So I needed a stopwatch that could do two things. It had to let me run multiple timers at once. And I had to be able to start the timer late and adjust it to the correct. So I made this app.
It is a very simple app. There’s a button to add more timers. And each timer can be adjusted upward. I didn’t need a minus function. Timers can also be removed by swiping on it from right to left.
By the way, this is the last Objective-C app I wrote.
Xcode 7.3 is here
I am in the process of upgrading to Xcode 7.3 which includes Swift 2.2.
This video explains how to pass data from one view controller to another view controller.
Swift static functions
Swift allows the same function name as static or non-static.
extension String { static func isDuck(s: String) -> Bool { if s == "duck" { return true } return false } func isDuck() -> Bool { return String.isDuck(self) } } let duck = "duck" let notduck = "not duck" print(duck.isDuck()) print(notduck.isDuck()) print(String.isDuck(duck))
Threads
It seems to me that newbie programmers don’t understand the idea of multi-threading and doing things asynchronously. This is an important concept when programming iOS application.
Threads are a way to do more than one thing at a time. Think of cooking. You put the bread in the over. While that is baking, you make coffee. When the bread is done, you deal with it. You would not want to sit and watch the bread bake. Threads are very similar.
Say you have an app that has to retrieve remote data from somewhere. Retrieving remote data takes a long time. You would not want your entire device to wait while the data downloads. Who knows how long that will take.
In iOS, you would tell it (the iOS operating system) what you wanted and leave a call back number. It is like saying “Hey iOS, get me weather info. When you get the data let me know. In the mean time, I’m going to do some other things”
Does this make it harder to create good apps? Yes. But if we did not do this, we would end up with a device that sometimes didn’t seem to be responsive and that would make us angry.
Guidelines for managing code
I'm creating an application in Xcode using Swift. I can implement all logic in one Controller. Unfortunately there is a lot of code and it results in a mess. I'd like some advice on how to reorganize the code to make it more manageable?
Recommendations
Putting everything in one file is definitely not the way to go.
Each screen should have its own view controller.
For the most part, only keep UI code in the view controller. This isn't a hard rule, but you should try to keep non UI code to a minimum.
Create utility classes to move code out of the controller.
Separate your data handling into its own class or sets of classes, in particular if it is a lot of code.
Use Storyboard as much as possible.
Name your functions and variables well so that someone looking at your code (including you) can easily see what it is attempting to do.
Take a look at these:
Model View Controller (MVC) and Model View Viewmodel (MVVM).
Using NSURLProtocol for Testing
By Roberto Osorio-Goenaga, iOS Developer
Unit testing networking code can be problematic, due mostly to its asynchronous nature. Using a staging server introduces lag and external factors that can cause your tests to run slowly, or not at all. Frameworks like OCMock exist to specify how an object responds to a specific query to address this behavior, but a mock object must still be set up for each type of behavior being mocked.
Using Apple’s NSURLProtocol, we can create a test suite that eschews these problems by mocking the response to our network calls centrally, essentially letting your test focus only on business logic. This protocol can be used not only with the built-in NSURLSession class, but can also be used to test classes and structs written with modern third party networking libraries, such as the popular Alamofire. In this article, we will look at mocking network responses in Swift for requests made using Alamofire. The sample project can be found on github.
NSURLProtocol’s main purpose is to extend URL loading to incorporate custom schemes or enhance existing ones. A secondary, yet extremely powerful, use of NSURLProtocol is to mock a server by sending canned responses back to callbacks and delegates. Say we have a very simple struct that uses Alamofire to make an HTTP GET request.
Fig 1 - A simple struct that serves as a REST client
The sample in Figure 1 creates a struct with an NSURL as an init parameter, and a sole method, getAvailableItems(), taking in a completion block as an argument, making a rest call to the NSURL and populating an array of MyItem in the block sent into it. From a testing perspective, we’d like to have a JSON response that matches the expected response, containing an object called items whose value pair is an array of strings. In order to make our tests as thorough and robust as possible, we’d also include at least two other mock responses: a JSON response that does not match this expectation, to test the else clause, and a garbage or erroneous response to check our error handling.
Fig 2 - A valid response
Fig 3 - A non-valid response
Fig 4 - A throw-away garbage response
Figures 2, 3 and 4 show a valid response for our purposes, a non-valid yet correct JSON response, and a throw-away string that isn’t even valid JSON, respectively. Without having to make a full-blown staging server, let’s see how we could go about testing these using NSURLProtocol.
To understand where NSURLProtocol fits into this problem, it’s important to look at a bit of the architecture Alamofire employs. Alamofire works as a singleton, as one can see from the above example. There is no instantiation required. Just feed a URL in, and make a request. Under the hood, the entity making the request is called the Manager. Manager is the entity that actually stores the URL and parameters, and is responsible for firing off an NSURLSession request abstracted from the caller class.
The manager for Alamofire can be initialized with a custom configuration of type NSURLSessionConfiguration, which has a property called protocolClasses, an array of NSURLProtocol members. By creating a new protocol that defines what happens when NSURLSession tries to reach a certain type of endpoint, loading it into the protocol array of a new configuration at index 0 (the default configuration), and initializing a new Manager object with this configuration, we can inject Alamofire with a simple, local mock server that will return whatever we want, given any request. Let’s start setting up a test class for our REST client by extending NSURLProtocol to respond to GET requests, and creating an Alamofire.Manager object with a custom NSURLSessionConfiguration that employs our protocol.
Fig 5 - Setting up a testing class for our client
Great, now we have an NSURLProtocol class that takes a GET request, checks the URL, and returns either a valid JSON response, or a simple “GARBAGE” response. This should allow us to test how our client responds. We still haven’t written any cases. We have a MyRESTClient property, as well as a Manager property. We also have a setup initial method that instantiates and loads our custom protocol into the manager instance. We now need a way to inject this manager instance into our Alamofire singleton. Let’s extend our client to the following.
Fig 6 - The REST client with an injectable “manager” parameter
We’ve added an initializer to our struct that allows us to send either a custom manager or nil into Alamofire. When the parameter is nil, the manager will load with its standard configuration. We also edited the request execution to be called via the manager we selected instead of directly through Alamofire. We can now add the following test case to our test class.
Fig 7 - Our first test case
In this test case, we create a new client, and give it our custom manager through the new initializer. We set a testing expectation, since the result comes back on a closure, and, after loading our itemsArray inside, fulfill the expectation. We tell the test case to wait for said expectation to be fulfilled, and, once it is, we make sure the itemsArray contains three items. If so, our test is successful, and our business logic is tested for getAvailableItems. Notice that we have used a bogus URL of “http://notNil”, which we have defined in the protocol to be selected in the conditional for populating the response correctly. To test the “garbage” case, we could write a test like the following.
Fig 8 - A test case for verifying a garbage response
In this second test case, the mocked URL of “http://nil” is not recognized, and the protocol responds by returning “GARBAGE”, thus not populating the response array. If our method is written correctly, it will call the closure with a nil array.
Fig 9 - A test case for verifying an incorrect response
In the third and final test case, our protocol class will return a “concepts” array instead of an “items” array, so the end result should still be a nil array in the closure.
As you can see, using NSURLProtocol we have created what amounts to a tiny server that responds to our requests and replies as specified, perfect for testing our asynchronous net calls. Now, go forth and test!
“Microsoft has launched its first Android smart-phone that is called Nokia X2. The device has lots of wonderful features to offer its users, so people, who want to purchase a budget smart-phone. To get information about the features and price of this device, check-out this blog..”
Finally,…
MD5 For Swift
This is a Swift function for doing MD5.
func md5(input: String) -> String { //var s = "The quick brown fox jumps over the lazy dog." let context = UnsafeMutablePointer.alloc(1) var digest = Array(count:Int(CC_MD5_DIGEST_LENGTH), repeatedValue:0) CC_MD5_Init(context) CC_MD5_Update(context, input, CC_LONG(input.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))) CC_MD5_Final(&digest, context) context.dealloc(1) let hexString = asHex(digest) print(hexString) return hexString }