Thursday, September 10, 2015

how to solve The model used to open the store is incompatible with the one used to create the store error on swift

It happened when I changed the model after several struggling during app working ( using old model)

how to solve.
I changed the simulator from 5s to 5. 
it works.


Friday, August 28, 2015

How to make an notification on swift

to make a notification app is simple.




1, add code on ViewContrller.swift like this.


import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    
        var localNotification:UILocalNotification = UILocalNotification()
        localNotification.alertAction = "Testing notifications"
        localNotification.alertBody = "hello world! "
        localNotification.fireDate = NSDate(timeIntervalSinceNow: 30)
        UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
    
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }



}



2, add code on AppDelegate.swift like this.

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.
        application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound |
            UIUserNotificationType.Alert | UIUserNotificationType.Badge, categories:nil))
        
        return true
    }


3, run your simulator. Don't forget to waiting at home screen.

I referred here
https://www.topcoder.com/blog/notifications-in-ios-8-using-swift/

how to fix an error of notification " time zone = (null), repeat interval = 0, repeat count = UILocalNotificationInfiniteRepeatCount, next fire date = user info = (null)} with an alert but haven't received permission from the user to display alerts by swift

When I tried to make a notification, I encountered this error showing on debug area.

(shows your timezone)  time zone = (null), repeat interval = 0, repeat count = UILocalNotificationInfiniteRepeatCount, next fire date = (shows your fire date)  user info = (null)} with an alert but haven't received permission from the user to display alerts

It means iOS8 needs user's permission.

How to solve;

add code in func application( application : ---- ) on AppDelegate.swift like following.

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.
        application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound |
            UIUserNotificationType.Alert | UIUserNotificationType.Badge, categories:nil))
        
        return true

    }

FYI
http://stackoverflow.com/questions/24100313/ask-for-user-permission-to-receive-uilocalnotifications-in-ios-8

How to go back to home screen on iOS Simulator

There's no home button on iOS simulator though it is super simple to go back to home screen.

just use: 

Cmd + Shift + H





Friday, August 14, 2015

How to add Core Data to existence project on swift

First, Open your APPDelegate.swift and import core data by writing as

import UIKit
import CoreData


Next, add Core data file by click "File" -> "New" -> "File" -> core data on your OS version.

Next, add  NSManagedObjectContext, NSManagedObjectModel and NSPersistentStoreCoordinator to your app delegate to AppDelegate.swift 
You need to change the name of your project name and Data model name.
This is the standard code which is generated when you start your new project.

    
    // MARK: - Core Data stack
    
    lazy var applicationDocumentsDirectory: NSURL = {
       
        let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
        return urls[urls.count-1] as! NSURL
        }()
    
    lazy var managedObjectModel: NSManagedObjectModel = {
   
        let modelURL = NSBundle.mainBundle().URLForResource("DATAMODELNAME", withExtension: "momd")!
        return NSManagedObjectModel(contentsOfURL: modelURL)!
        }()
    
    lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
    
        var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
        let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("PROJECTNAME.sqlite")
        var error: NSError? = nil
        var failureReason = "There was an error creating or loading the application's saved data."
        if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
            coordinator = nil
        
            var dict = [String: AnyObject]()
            dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
            dict[NSLocalizedFailureReasonErrorKey] = failureReason
            dict[NSUnderlyingErrorKey] = error
            error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
       
            NSLog("Unresolved error \(error), \(error!.userInfo)")
            abort()
        }
        
        return coordinator
        }()
    
    lazy var managedObjectContext: NSManagedObjectContext? = {
   
        let coordinator = self.persistentStoreCoordinator
        if coordinator == nil {
            return nil
        }
        var managedObjectContext = NSManagedObjectContext()
        managedObjectContext.persistentStoreCoordinator = coordinator
        return managedObjectContext
        }()
    
    // MARK: - Core Data Saving support
    
    func saveContext () {
        if let moc = self.managedObjectContext {
            var error: NSError? = nil
            if moc.hasChanges && !moc.save(&error) {
    
                NSLog("Unresolved error \(error), \(error!.userInfo)")
                abort()
            }
        }
    }





Next, add "self.saveContext()" to applicationWillTerminate 
    func applicationWillTerminate(application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.

        self.saveContext()

it's done!


I referred to this website for this work. please check 
http://craig24.com/2014/12/how-to-add-core-data-to-an-existing-swift-project-in-xcode/#comment-34489


Thursday, August 13, 2015

How to fix the error " Unsupported Configuration Scene is unreachable due to lack of entry points and does not have an identifier for runtime access via -instantiateViewControllerWithIdentifier"

"Unsupported Configuration     Scene is unreachable due to lack of entry points and does not have an identifier  for runtime access via -instantiateViewControllerWithIdentifier"

I encounter it and didn't know what's happen.
but i found this is very common error when we use screen transition.
Xcode complain that there are no initial screen has been assigned.

if you are using "Navigation Controller" , then assign it as a " initial View Controller"
for assign, just check the checkbox as below.

easy.





Wednesday, August 12, 2015

How to create transition on swift


prepare two view controller on storyboard.
set button on first one.
ctrl + drag from the button to second view controller
select "show"

that's all.
this is primitive  way but we don't need any code nor navigation controller.


How to show Map on swift.

very simple.

add "MapKit View" from object library
add "MapKit framework" from Build Phases, " Link Binary With Libraries" by click "+" and chose MapKit framework.
add "import MapKit" on ViewController.swift


that's all.
great is MapKit framework.

Tuesday, August 11, 2015

How to Drop the Pin to the Map on swift


write in the "override fun viewDidLoad(){

        let AAA = MKPointAnnotation()
        let centerCoordinate = CLLocationCoordinate2D(latitude: 10.79661075, longitude: 106.69064892)
            AAA.coordinate = centerCoordinate
            AAA.title = "test"
            AAA.subtitle = "abced"
        self.theMap.addAnnotation(AAA)


"addAnnotation" helps you to drop the pin on the map.

*don't forget to declare the Map = MKMapView with import MapKit.

Sunday, August 9, 2015

How to set Photo expand as much as possible on imagecell

1. select target image cell on document Outline
2. remove check from "Constrain to margins"
3. click four red constrains line beside of number.
4. set 0 to each
5. click Add 4 Constrains




Saturday, August 8, 2015

how to create "method" on swift

method is written like this

func  MethodName (Argument Datatype) -> ReturnValue {
      code

}


how to add MapKit


1. choose project on the left menu
2. choose target 
3. click "+" of Link Binary --
4. select MapKit Framework
5. Open the ViewController and write "import MapKit"



how to open the Photo Library on iPhone

this is the minimum.

import UIKit

class ViewController: UIViewController, UIImagePickerControllerDelegate ,UINavigationControllerDelegate{
    @IBAction func openPhotoLibrary(sender: UIButton) {
        var photoPicker = UIImagePickerController()
        photoPicker.delegate = self
        photoPicker.sourceType = .PhotoLibrary
        
        self.presentViewController( photoPicker, animated: true, completion: nil)
        

    }

@https://www.youtube.com/watch?v=leyk3QOYJF0


complete ver of this instruction video
import UIKit

class ViewController: UIViewController, UIImagePickerControllerDelegate ,UINavigationControllerDelegate{
    
    var photoImageView = UIImageView(frame: CGRectMake(40, 120, 200, 200))
    
    @IBAction func openPhotoLibrary(sender: UIButton) {
        var photoPicker = UIImagePickerController()
        photoPicker.delegate = self
        photoPicker.sourceType = .PhotoLibrary
        
        self.presentViewController( photoPicker, animated: true, completion: nil)
        
    }

   override func viewDidLoad() {
        super.viewDidLoad()
        self.view.addSubview(photoImageView)
    
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
   }
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject: AnyObject]) {
        
        photoImageView.image = info [UIImagePickerControllerOriginalImage]as? UIImage
        self.dismissViewControllerAnimated(false, completion: nil)
    }

}



how to solve the error of "Failed to instantiate the default view controller for UIMainStoryboardFile ‘Main’ – perhaps the designated entry point is not set?


stucked for an hour by this very fundamental error.
it's so simple to fix actually.
Check the "is initial View Controller".







Failed to instantiate the default view controller for UIMainStoryboardFile ‘Main’ – perhaps the designated entry point is not set?

how to create code for taking photo

success as a part of project.
http://www.ioscreator.com/tutorials/take-photo-tutorial-ios8-swift
still struggling with this though ( http://www.techotopia.com/index.php/An_Example_Swift_iOS_8_iPhone_Camera_Application)

import UIKit

var imagePicker: UIImagePickerController!

class ViewController: UIViewController ,UINavigationControllerDelegate, UIImagePickerControllerDelegate{



    @IBOutlet var imageView: UIImageView!
    
    @IBAction func takePhoto(sender: UIButton) {
        imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = .Camera
        
        presentViewController(imagePicker, animated: true, completion: nil)
        
    }
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject :AnyObject]){

    imagePicker.dismissViewControllerAnimated(true, completion: nil)
    imageView.image = info [UIImagePickerControllerOriginalImage] as? UIImage
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}


Friday, August 7, 2015

isEqualToString have already been over on swift?

an error message showed that :
"String does not have  member named isEqualToString"

checked internet and found below.

I just change the "isEqualToString" to "is Equal", no showing error anymore but not sure it is correct or not.



http://stackoverflow.com/questions/24096708/isequaltostring-in-swift

7 Answers

up vote78down voteaccepted
With Swift you don't need anymore to check the equality with isEqualToString
You can now use ==
Example: 
let x = "hello"
let y = "hello"
let isEqual = (x == y)


Swift Tutorial for iOS: Part 4 - MapKit App Displaying World's Tallest Church | AppShocker

Swift Tutorial for iOS: Part 4 - MapKit App Displaying World's Tallest Church | AppShocker


done.
simple but good to know how to make a pin with it's annotation..


import UIKit
import MapKit

class ViewController: UIViewController, MKMapViewDelegate {
    @IBOutlet weak var theMapview: MKMapView!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        var latitude:CLLocationDegrees = 48.399193
        var longitude:CLLocationDegrees = 9/993341
        
        //zoom
        var latDelta:CLLocationDegrees = 0.01
        var longDelta:CLLocationDegrees = 0.01
        
        var theSpan:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, longDelta)
        
        var churchLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
        
        var theRegion: MKCoordinateRegion = MKCoordinateRegionMake(churchLocation, theSpan)
        
        self.theMapview.setRegion(theRegion, animated: true)
        
        var theUlmMinsterAnnotation = MKPointAnnotation()
        theUlmMinsterAnnotation.coordinate = churchLocation
        
        theUlmMinsterAnnotation.title = "ulm Minster"
        theUlmMinsterAnnotation.subtitle = "A famous church in Germany"
        
        self.theMapview.addAnnotation(theUlmMinsterAnnotation)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }



}

https://www.youtube.com/watch?v=uB100xVS_Yc

Thursday, August 6, 2015

how to add Navigation Controller


check your view controller is activated.
click Editor > embed in > Navigation Controller

Wednesday, August 5, 2015

how to resize the zoom level at mapping

  let spanX = 0.007
  let spanY = 0.007
  var newRegion = MKCoordinateRegion(center: theMap.userLocation.coordinate, span: MKCoordinateSpanMake(spanX, spanY))
   theMap.setRegion(newRegion, animated: true)

change the value of span.

other tracking system is here
http://www.johnmullins.co/blog/2014/08/14/location-tracker-with-maps/

Tuesday, August 4, 2015

how to output a sound to speaker

create instans
AVAudioSession.sharedInstance() 

add 
session.overrideOutputAudioPort(AVAudioSessionPortOverride.Speaker, error: nil)



http://stackoverflow.com/questions/28630833/change-avaudioplayer-output-to-speaker-in-swift

Monday, August 3, 2015

how to solved libc++abi.dylib: terminating with uncaught exception of type NSException

FYI
http://stackoverflow.com/questions/26442414/libcabi-dylib-terminating-with-uncaught-exception-of-type-nsexception-lldb

why it happened:
I drag the button on the main story board to view controller with define the name and action for UIbutton.
I realized I wrong the name and rename & drag again.

I found how to solved it after duplicating it.


Sunday, August 2, 2015

HOW TO CHANGE the NAME of view controller.swift


when the name of View Controller has been changed, 
change also the name at Comment section and class at the third line.

finally, back to the story board and select the new name as following.

That's all.
@Udacity

How to Play Audio in Swift


var filePath = NSBundle.mainBundle().pathForResource("movie_quote", ofType: "mp3"){
            var filePathUrl = NSURL.fileURLWithPath(filePath)
            audioPlayer = AVAudioPlayer(contentsOfURL: filePathUrl, error: nil)

            audioPlayer.enableRate=true

with this code

File -> add new file -> select audio file -> move to "supporting files " on Navigator.
the file is located to "movie_quote" 


2, 

    @IBAction func FastButton(sender: UIButton) {
        audioPlayer.stop()
        audioPlayer.rate = 2.0
        audioPlayer.play()


Action on User Interface Button with above code.
rate  enable to change the pitch.

today's Udacity's lecture.