Parse api's saveInBackground not working in Swift 3 - heroku

I'm testing my parse code on Heroku because of parse.com's shutdown. In Swift 3, saveInBackgroundWithBlock has been renamed to saveInBackground, so I updated that syntax in my code as well as the 'NS' prefix issue. But an error still remains. As a learner, I can't possibly take care of this further. I want a kind person to help me solve this. Thanks in advance.
import UIKit
import Parse
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let object = PFObject(className: "testObject")
object["name"] = "Bill"
object["lastname"] = "Alexander"
object.saveInBackground(block: { (success, error) in
if success {
print("Saved in server")
} else {
print(error!)
}
})
}
Here is also my screenshot:
'Expected declaration' error screenshot

You almost there, The syntax is just slightly incorrect. Also check against the error for any issues.
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let object = PFObject(className: "testObject")
object["name"] = "Bill"
object["lastname"] = "Alexander"
object.saveInBackground { (success, error) -> Void in
if error == nil {
print("Saved in server")
} else {
print(error!)
}
}
}

Related

Getting a fatal error when trying to play sound in Swift

I have worked my way through this tutorial here. One of the last things you do is have a button make sound when it is pressed. I wanted to then continue using that same logic to make a sound board app. However when I stripped the non-essential parts besides it making noise inside a new project I started getting a fatal error.
Here is my ViewController.swfit file:
import UIKit
import AVFoundation
class ViewController: UIViewController {
var sample : AVAudioPlayer?
func setupAudioPlayerWithFile(file:NSString, type:NSString) -> AVAudioPlayer? {
//1
let path = NSBundle.mainBundle().pathForResource(file as String, ofType: type as String)
let url = NSURL.fileURLWithPath(path!)
//2
var audioPlayer:AVAudioPlayer?
// 3
do {
try audioPlayer = AVAudioPlayer(contentsOfURL: url)
} catch {
print("Player not available")
}
return audioPlayer
}
override func viewDidLoad() {
super.viewDidLoad()
if let sample = self.setupAudioPlayerWithFile("Stomach", type:"aif") {
self.sample = sample
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func buttonPressed() {
sample?.play()
}
}
Here is my project when the fatal error hits
I have also tried this solution but I got errors as well.
I am running on El Capitan 10.11.3 with Xcode 7.3
Have you included the an audio file named "Stomach.aif" in your project? If not, pathForResource will return nil and you'll crash when attempting to force unwrap that path. You can use a safer version of this function, although if it can't locate that file it still won't play the audio On the bright side it shouldn't crash.
func setupAudioPlayerWithFile(file:NSString, type:NSString) -> AVAudioPlayer? {
var audioPlayer:AVAudioPlayer? = nil
if let path = NSBundle.mainBundle().pathForResource(file as String, ofType: type as String) {
let url = NSURL.fileURLWithPath(path)
do {
try audioPlayer = AVAudioPlayer(contentsOfURL: url)
} catch {
print("Player not available")
}
}
return audioPlayer
}

Error "Thread 1: breakpoint 2.1"

I am working on a REST API Manager. It is giving an error and I am not able to fix it. The error I got is given below as highlighted.
import Foundation
import Alamofire
import SwiftyJSON
class RestApiManager {
var resources: JSON = [
"resources": [
"resourceA": []
]
]
let apiUrl: String
let apiUsername: String
let apiPassword: String
init(apiUrl: String, apiUsername: String, apiPassword: String) {
self.apiUrl = apiUrl
self.apiUsername = apiUsername
self.apiPassword = apiPassword
getApiResourceA() { responseObject, error in
let resourceA = JSON(responseObject!)
self.resources["resources"]["resourceA"] = resourceA
}
}
func collectDataFromApi(completionHandler: (responseObject: NSDictionary?, error: NSError?) -> ()) {
prepareHttpRequest(completionHandler)
}
func prepareHttpRequest(completionHandler: (responseObject: NSDictionary?, error: NSError?) -> ()) {
let alamofireRequest = Alamofire.request(.GET, "\(self.apiUrl)")
alamofireRequest.authenticate(user: self.apiUsername, password: self.apiPassword)
alamofireRequest.responseJSON { request, response, responseObject, error in
completionHandler(responseObject: responseObject as? NSDictionary, error: error)
}
}
func getAllResources() -> JSON {
return self.resources
}
func getApiResourceA(completion: (responseObject: NSDictionary?, error: NSError?) -> ()) {
collectDataFromApi() { responseObject, error in
completion(responseObject: responseObject, error: error)
}
}
}
And when I call this class to get the resources:
override func viewDidLoad() {
super.viewDidLoad()
if record != nil {
let url = record?.url
let username = record?.username
let password = record?.password
let restApiManager = RestApiManager(apiUrl: url!, apiUsername: username!, apiPassword: password!) // This line seems buggy
let delay = 10.0 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(time, dispatch_get_main_queue()) {
let Resources = restApiManager.getAllResources()
let ResourceA = Resources["resources"]["resourceA"]
}
}
}
The line I commented prints:
Thread 1: breakpoint 2.1
I need suggestions for fix that error. Any suggestions are very much appreciated
You may have accidentally set a breakpoint without noticing.
Click and drag the blue tick representing the breakpoint outside of the gutter to erase it.
I was getting same error when I accidentally activated Breakpoint in my Xcode.
To resolve issue, simply unblock blue icon.

unexpectedly found nil while unwrapping an Optional value(optional binding)

import UIKit
import Parse
class HomePageViewController: UIViewController, UITableViewDelegate {
#IBOutlet weak var homPageTableView: UITableView!
var imageFiles = [PFFile]()
var imageText = [String]()
override func viewDidLoad() {
super.viewDidLoad()
// DO any additional setup after loading the view
var query = PFQuery(className: "Posts")
query.orderByAscending("createdAt")
query.findObjectsInBackgroundWithBlock {
(posts : [AnyObject]?, error : NSError?) -> Void in
if error == nil {
//success fetxhing objects
println(posts?.count)
for post in posts! {
self.imageFiles.append(post["imageFile"] as! PFFile) ---------error here
self.imageText.append(post["imageText"] as! String)
}
println(self.imageFiles.count)
}else{ println(error)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
As a title, It is keep saying "unexpectedly found nil while unwrapping an Optional value" at the line I draw.
There are a lot of questions about this, it is hard to read code for me, And even if I undertood, mine didn't go right.
where should I use optional binding?
And can u explain it with really easy example what is optional binding?
Thank you
Your post dictionary does not contain an imageFile key. When you access a dictionary using post["imageFile"] the result is the value (if the key exists) and nil (if the key does not exist). You can distinguish between these cases using
if let imageFile = post["imageFile"],
let imageText = post["imageText"] {
self.imageFiles.append(imageFile as! PFFile)
self.imageText.append(imageText as! String)
} else {
print("imageFile and/or imageText missing from \(post)")
}
You need to unwrap your posts before looping through them because posts: [AnyObject]? is optional.
if error == nil {
if let postData = posts{
//success fetxhing objects
println(postData?.count)
for post in postData! {
self.imageFiles.append(post["imageFile"] as! PFFile)
self.imageText.append(post["imageText"] as! String)
}
println(self.imageFiles.count)
}
}else{
println(error)
}

Why do I get this error "fatal error: unexpectedly found nil while unwrapping an Optional value" in Swift Xcode?

I'm trying to ad an Ad network called StartApps and 'Im following this guideline.(https://github.com/StartApp-SDK/Documentation/wiki/iOS-Swift-InApp-Documentation#step3)
The problem is that I get this error:
fatal error: unexpectedly found nil while unwrapping an Optional value
At
viewController.startAppAd!.showAd()
in my GameScene.swift. Why does this happen. Thanks!
class GameViewController: UIViewController {
var startAppAd: STAStartAppAd?
override func viewDidLoad() {
super.viewDidLoad()
startAppAd = STAStartAppAd()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
startAppAd!.loadAd()
}
//Im calling the function showsAds() in the GameScene.swift file
class GameScene: SKScene {
var viewController = GameViewController()
override func didMoveToView() {
}
// interstitial ads randomnly appear after hero hits enemy
func interstitialAdsRandom(){
var randomAd = Int(arc4random() % 2)
println(randomAd)
if randomAd == 0 {
viewController.startAppAd!.showAd()
println("showad")
}
}
}
}
You get the error because you are force-unwrapping the variable startAppAd. That is what force-unwrapping does.
If you change that exclamation point to a question mark, it will make it so that the method call is skipped if the optional contains nil.
startAppAd?.loadAd()
If you want to write the best code, you should use "if let" syntax, known as optional binding:
if let startAppAd = startAppAd
{
startAppAd.loadAd()
}
else
{
//startAppAd is nil. Handle that error case
}

Delegates in swift?

How does one go about making a delegate, i.e. NSUserNotificationCenterDelegate in swift?
Here's a little help on delegates between two view controllers:
Step 1: Make a protocol in the UIViewController that you will be removing/will be sending the data.
protocol FooTwoViewControllerDelegate:class {
func myVCDidFinish(_ controller: FooTwoViewController, text: String)
}
Step2: Declare the delegate in the sending class (i.e. UIViewcontroller)
class FooTwoViewController: UIViewController {
weak var delegate: FooTwoViewControllerDelegate?
[snip...]
}
Step3: Use the delegate in a class method to send the data to the receiving method, which is any method that adopts the protocol.
#IBAction func saveColor(_ sender: UIBarButtonItem) {
delegate?.myVCDidFinish(self, text: colorLabel.text) //assuming the delegate is assigned otherwise error
}
Step 4: Adopt the protocol in the receiving class
class ViewController: UIViewController, FooTwoViewControllerDelegate {
Step 5: Implement the delegate method
func myVCDidFinish(_ controller: FooTwoViewController, text: String) {
colorLabel.text = "The Color is " + text
controller.navigationController.popViewController(animated: true)
}
Step 6: Set the delegate in the prepareForSegue:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "mySegue" {
let vc = segue.destination as! FooTwoViewController
vc.colorString = colorLabel.text
vc.delegate = self
}
}
And that should work. This is of course just code fragments, but should give you the idea. For a long explanation of this code you can go over to my blog entry here:
segues and delegates
If you are interested in what's going on under the hood with a delegate I did write on that here:
under the hood with delegates
Delegates always confused me until I realized that a delegate is just a class that does some work for another class. It's like having someone else there to do all the dirty work for you that you don't want to do yourself.
I wrote a little story to illustrate this. Read it in a Playground if you like.
Once upon a time...
// MARK: Background to the story
// A protocol is like a list of rules that need to be followed.
protocol OlderSiblingDelegate: class {
// The following command (ie, method) must be obeyed by any
// underling (ie, delegate) of the older sibling.
func getYourNiceOlderSiblingAGlassOfWater()
}
// MARK: Characters in the story
class BossyBigBrother {
// I can make whichever little sibling is around at
// the time be my delegate (ie, slave)
weak var delegate: OlderSiblingDelegate?
func tellSomebodyToGetMeSomeWater() {
// The delegate is optional because even though
// I'm thirsty, there might not be anyone nearby
// that I can boss around.
delegate?.getYourNiceOlderSiblingAGlassOfWater()
}
}
// Poor little sisters have to follow (or at least acknowledge)
// their older sibling's rules (ie, protocol)
class PoorLittleSister: OlderSiblingDelegate {
func getYourNiceOlderSiblingAGlassOfWater() {
// Little sis follows the letter of the law (ie, protocol),
// but no one said exactly how she had to respond.
print("Go get it yourself!")
}
}
// MARK: The Story
// Big bro is laying on the couch watching basketball on TV.
let bigBro = BossyBigBrother()
// He has a little sister named Sally.
let sally = PoorLittleSister()
// Sally walks into the room. How convenient! Now big bro
// has someone there to boss around.
bigBro.delegate = sally
// So he tells her to get him some water.
bigBro.tellSomebodyToGetMeSomeWater()
// Unfortunately no one lived happily ever after...
// The end.
In review, there are three key parts to making and using the delegate pattern.
the protocol that defines what the worker needs to do
the boss class that has a delegate variable, which it uses to tell the worker class what to do
the worker class that adopts the protocol and does what is required
Real life
In comparison to our Bossy Big Brother story above, delegates are often used for the following practical applications:
Communication: one class needs to send some information to another class.
Code example 1: sending data from one view controller to another
Code example 2: sending text input from a custom keyboard to a text field
Customization: one class wants to allow another class to customize it.
The great part is that these classes don't need to know anything about each other beforehand except that the delegate class conforms to the required protocol.
I highly recommend reading the following two articles. They helped me understand delegates even better than the documentation did.
What is Delegation? – A Swift Developer’s Guide
How Delegation Works – A Swift Developer’s Guide
One more note
Delegates that reference other classes that they do not own should use the weak keyword to avoid strong reference cycles. See this answer for more details.
It is not that different from obj-c.
First, you have to specify the protocol in your class declaration, like following:
class MyClass: NSUserNotificationCenterDelegate
The implementation will look like following:
// NSUserNotificationCenterDelegate implementation
func userNotificationCenter(center: NSUserNotificationCenter, didDeliverNotification notification: NSUserNotification) {
//implementation
}
func userNotificationCenter(center: NSUserNotificationCenter, didActivateNotification notification: NSUserNotification) {
//implementation
}
func userNotificationCenter(center: NSUserNotificationCenter, shouldPresentNotification notification: NSUserNotification) -> Bool {
//implementation
return true
}
Of course, you have to set the delegate. For example:
NSUserNotificationCenter.defaultUserNotificationCenter().delegate = self;
I got few corrections to post of #MakeAppPie
First at all when you are creating delegate protocol it should conform to Class protocol. Like in example below.
protocol ProtocolDelegate: class {
func myMethod(controller:ViewController, text:String)
}
Second, your delegate should be weak to avoid retain cycle.
class ViewController: UIViewController {
weak var delegate: ProtocolDelegate?
}
Last, you're safe because your protocol is an optional value. That means its "nil" message will be not send to this property. It's similar to conditional statement with respondToselector in objC but here you have everything in one line:
if ([self.delegate respondsToSelector:#selector(myMethod:text:)]) {
[self.delegate myMethod:self text:#"you Text"];
}
Above you have an obj-C example and below you have Swift example of how it looks.
delegate?.myMethod(self, text:"your Text")
Here's a gist I put together. I was wondering the same and this helped improve my understanding. Open this up in an Xcode Playground to see what's going on.
protocol YelpRequestDelegate {
func getYelpData() -> AnyObject
func processYelpData(data: NSData) -> NSData
}
class YelpAPI {
var delegate: YelpRequestDelegate?
func getData() {
println("data being retrieved...")
let data: AnyObject? = delegate?.getYelpData()
}
func processYelpData(data: NSData) {
println("data being processed...")
let data = delegate?.processYelpData(data)
}
}
class Controller: YelpRequestDelegate {
init() {
var yelpAPI = YelpAPI()
yelpAPI.delegate = self
yelpAPI.getData()
}
func getYelpData() -> AnyObject {
println("getYelpData called")
return NSData()
}
func processYelpData(data: NSData) -> NSData {
println("processYelpData called")
return NSData()
}
}
var controller = Controller()
DELEGATES IN SWIFT 2
I am explaining with example of Delegate with two viewControllers.In this case, SecondVC Object is sending data back to first View Controller.
Class with Protocol Declaration
protocol getDataDelegate {
func getDataFromAnotherVC(temp: String)
}
import UIKit
class SecondVC: UIViewController {
var delegateCustom : getDataDelegate?
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func backToMainVC(sender: AnyObject) {
//calling method defined in first View Controller with Object
self.delegateCustom?.getDataFromAnotherVC(temp: "I am sending data from second controller to first view controller.Its my first delegate example. I am done with custom delegates.")
self.navigationController?.popViewControllerAnimated(true)
}
}
In First ViewController Protocol conforming is done here:
class ViewController: UIViewController, getDataDelegate
Protocol method definition in First View Controller(ViewController)
func getDataFromAnotherVC(temp : String)
{
// dataString from SecondVC
lblForData.text = dataString
}
During push the SecondVC from First View Controller (ViewController)
let objectPush = SecondVC()
objectPush.delegateCustom = self
self.navigationController.pushViewController(objectPush, animated: true)
First class:
protocol NetworkServiceDelegate: class {
func didCompleteRequest(result: String)
}
class NetworkService: NSObject {
weak var delegate: NetworkServiceDelegate?
func fetchDataFromURL(url : String) {
delegate?.didCompleteRequest(result: url)
}
}
Second class:
class ViewController: UIViewController, NetworkServiceDelegate {
let network = NetworkService()
override func viewDidLoad() {
super.viewDidLoad()
network.delegate = self
network.fetchDataFromURL(url: "Success!")
}
func didCompleteRequest(result: String) {
print(result)
}
}
Very easy step by step (100% working and tested)
step1: Create method on first view controller
func updateProcessStatus(isCompleted : Bool){
if isCompleted{
self.labelStatus.text = "Process is completed"
}else{
self.labelStatus.text = "Process is in progress"
}
}
step2: Set delegate while push to second view controller
#IBAction func buttonAction(_ sender: Any) {
let secondViewController = self.storyboard?.instantiateViewController(withIdentifier: "secondViewController") as! secondViewController
secondViewController.delegate = self
self.navigationController?.pushViewController(secondViewController, animated: true)
}
step3: set delegate like
class ViewController: UIViewController,ProcessStatusDelegate {
step4: Create protocol
protocol ProcessStatusDelegate:NSObjectProtocol{
func updateProcessStatus(isCompleted : Bool)
}
step5: take a variable
var delegate:ProcessStatusDelegate?
step6: While go back to previous view controller call delegate method so first view controller notify with data
#IBAction func buttonActionBack(_ sender: Any) {
delegate?.updateProcessStatus(isCompleted: true)
self.navigationController?.popViewController(animated: true)
}
#IBAction func buttonProgress(_ sender: Any) {
delegate?.updateProcessStatus(isCompleted: false)
self.navigationController?.popViewController(animated: true)
}
Simple Example:
protocol Work: class {
func doSomething()
}
class Manager {
weak var delegate: Work?
func passAlong() {
delegate?.doSomething()
}
}
class Employee: Work {
func doSomething() {
print("Working on it")
}
}
let manager = Manager()
let developer = Employee()
manager.delegate = developer
manager.passAlong() // PRINTS: Working on it
Delegates are a design pattern that allows one object to send messages to another object when a specific event happens.
Imagine an object A calls an object B to perform an action. Once the action is complete, object A should know that B has completed the task and take necessary action, this can be achieved with the help of delegates!
Here is a tutorial implementing delegates step by step in swift 3
Tutorial Link
Here is real life delegate scenario
Lets make our own UITextField and UITextFieldDelegate
// THE MYSTERIOUS UITEXTFIELD
protocol UITextFieldDelegate {
func textFieldDidChange(_ textField: UITextField) -> Void
}
class UITextField {
var delegate: UITextFieldDelegate?
private var mText: String?
var text: String? {
get {
return mText
}
}
init(text: String) {
}
init() {
}
func setText(_ text: String) {
mText = text
delegate?.textFieldDidChange(self)
}
}
// HERE IS MY APP
class Main {
let textfield = UITextField()
func viewDidLoad() {
print("viewDidLoad")
textfield.delegate = self
textfield.setText("Hello")
}
}
extension Main: UITextFieldDelegate {
func textFieldDidChange(_ textField: UITextField) {
print(textField.text ?? "No string")
}
}
let main = Main()
main.viewDidLoad()
Here Simple Code Example of Delegate:
//MARK: - Protocol ShowResult
protocol ShowResult: AnyObject {
func show(value: Int)
}
//MARK: - MyOperation Class
class MyOperation {
weak var delegate: ShowResult?
func sum(fNumber: Int, sNumber: Int) {
delegate?.show(value: fNumber + sNumber)
}
}
//MARK: - ViewController Class
class ViewController: UIViewController,ShowResult {
var myOperation: MyOperation?
override func viewDidLoad() {
super.viewDidLoad()
loadMyOperation()
myOperation?.delegate = self
myOperation?.sum(fNumber: 100, sNumber: 20)
}
private func loadMyOperation() {
if myOperation == nil {
myOperation = MyOperation()
}
}
func show(value: Int) {
print("value: \(value)")
}
}
The solutions above seemed a little coupled and at the same time avoid reuse the same protocol in other controllers, that's why I've come with the solution that is more strong typed using generic type-erasure.
#noreturn public func notImplemented(){
fatalError("not implemented yet")
}
public protocol DataChangedProtocol: class{
typealias DataType
func onChange(t:DataType)
}
class AbstractDataChangedWrapper<DataType> : DataChangedProtocol{
func onChange(t: DataType) {
notImplemented()
}
}
class AnyDataChangedWrapper<T: DataChangedProtocol> : AbstractDataChangedWrapper<T.DataType>{
var base: T
init(_ base: T ){
self.base = base
}
override func onChange(t: T.DataType) {
base.onChange(t)
}
}
class AnyDataChangedProtocol<DataType> : DataChangedProtocol{
var base: AbstractDataChangedWrapper<DataType>
init<S: DataChangedProtocol where S.DataType == DataType>(_ s: S){
self.base = AnyDataChangedWrapper(s)
}
func onChange(t: DataType) {
base.onChange(t)
}
}
class Source : DataChangedProtocol {
func onChange(data: String) {
print( "got new value \(data)" )
}
}
class Target {
var delegate: AnyDataChangedProtocol<String>?
func reportChange(data:String ){
delegate?.onChange(data)
}
}
var source = Source()
var target = Target()
target.delegate = AnyDataChangedProtocol(source)
target.reportChange("newValue")
output: got new value newValue
In swift 4.0
Create a delegate on class that need to send some data or provide some functionality to other classes
Like
protocol GetGameStatus {
var score: score { get }
func getPlayerDetails()
}
After that in the class that going to confirm to this delegate
class SnakesAndLadders: GetGameStatus {
func getPlayerDetails() {
}
}
In swift 5
I am a beginner, I think this is easiest way to understand in practical scenario
Note:Any improvisations are most appreciated
protocol APIService {
func onSuccessResponse() -> AnyObject
func onFailureResponse() -> AnyObject
}
class APIHelper{
var delegate : APIService?
func postUsersDataAPI() {
//assuming API communication is success
if(success){
let _: AnyObject? = delegate?.onSuccessResponse()
}else if(failure){
let _: AnyObject? = delegate?.onFailureResponse()
}
}
func getAllUsersAPI() {
//assuming API communication is success
if(success){
let _: AnyObject? = delegate?.onSuccessResponse()
}else if(failure){
let _: AnyObject? = delegate?.onFailureResponse()
}
}
}
class ViewController:UIViewController,APIService {
func onSuccessResponse() -> AnyObject {
print("onSuccessResponse") as AnyObject
}
func onFailureResponse() -> AnyObject {
print("onFailureResponse") as AnyObject
}
#IBAction func clickBtnToPostUserData(_ sender: Any) {
let apiHelper = APIHelper()
apiHelper.delegate = self
apiHelper.postAPI()
}

Resources