print("#Bonjour le monde...\n")
let pi = 3.141592
print("#La valeur de pi est \(pi)\n")
let a=3, b=7
print("#\(a) + \(b) = \(a+b)\n")
let unNom = "TIM le magnifique"
print("#\(unNom) dit: Bonjour ");print("à tous!\n")
Note: voici comment désactiver les messages superflus de la console:
Dans Product>>Scheme>>Edit Scheme…>>Run…Arguments,
Ajouter cette variable d’environment:
Name: OS_ACTIVITY_MODE, Value: disable
let uneChaineRO = "Je suis une chaine en lecture seule"
var uneChaineRW = "Je suis une chaine en lecture écriture"
var uneChaineOC:NSString = "Je suis une chaine Objective-C"
print("Il y a \(countElements(uneChaineRO)) caractères dans uneChaineRO")
print("Il y a \(String(uneChaineOC.length)) caractères dans uneChaineOC")
let perso = "Fantomas" let persoForce = 17 var message = "Mon nom est \(perso) et j'ai \(persoForce) de force."
var msg:String
let pi = 3.141592
msg = "Bienvenue " + "Au cours d'intro "
msg += "du langage Swift. PI = " + String(pi)
var res = ""
for car in msg {
res += car
}
// Étant donné le fichier suivant:
<array>
<dict>
<key>nom</key>
<string>Paul</string>
<key>photo</key>
<string>image01.png</string>
<key>dette</key>
<real>10.99</real>
</dict>
...
</array>
// Créer un tableau avec méthode: Swift + Foundation
let pathFichierPlist = NSBundle.mainBundle().pathForResource("liste des amis", ofType: "plist")!
amis = NSArray(contentsOfFile: pathFichierPlist)
/// Méthode 100% swift (pas encore au point en version beta)
var tabloPerso:String[] = []
let path = NSBundle.mainBundle().pathForResource("personnages", ofType: "plist")
tabloPerso = NSArray(contentsOfFile: path) as String[]
print(tabloPerso)
tabloPerso.append("Tintin")
print(tabloPerso)
print(tabloPerso[tabloPerso.count - 1])
// Créer un tableau de 'Dictionary' à partir d'un fichier plist
// Définition du tableau
var amis:[Dictionary<String,String>]!
...
// Affectation à partir d'un fichier
amis = NSArray(contentsOfFile: NSBundle.mainBundle().pathForResource("liste des amis", ofType: "plist")!) as [Dictionary<String,String>]
let _image = UIImage(named:"paysage") self.uneImage.image = image // ou bien self.imageView.image = UIImage(named:"image.png")
override func prefersStatusBarHidden() -> Bool {
return true
}
let selection =(sender as UISegmentedControl).selectedSegmentIndex
@IBAction func retourParent(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion:nil);
}
// ********************************************************************
func tableView(tableView: UITableView, numberOfRowsInSection:NSInteger) -> Int
// ********************************************************************
{
return tablo.count
} // numberOfRowsInSection
// ********************************************************************
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell!
// ********************************************************************
{
//variable type is inferred
var cell = tableView.dequeueReusableCellWithIdentifier("CELL") as? UITableViewCell
if !cell {
cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "modeleCellule")
} // !cell
//we know that cell is not empty now so we use ! to force unwrapping
cell!.textLabel.text = tablo[indexPath.row]
cell!.detailTextLabel.text = "Personnage de Tintin"
cell!.imageView.image = UIImage(named:"lezard")
return cell
} // cellForRowAtIndexPath
// ********************************************************************
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell!
// ********************************************************************
{
//Le type de la variable est inféré.
var cell = tableView.dequeueReusableCellWithIdentifier("modeleCellule") as? CellulePerso
if cell !=nil { // Si nil alors
cell = CellulePerso(style: UITableViewCellStyle.Value1, reuseIdentifier: "modeleCellule")
} // !cell
//À ce point ci, cell n'est pas nil. Il faut utiliser ! pour la déballer
cell!.c1.text = tablo[indexPath.row]
cell!.c2.text = "Personnage de Tintin"
cell!.uneImage.image = UIImage(named:"lezard")
return cell
} // cellForRowAtIndexPath
// ********************************************************************
func collectionView(collectionView: UICollectionView?, numberOfItemsInSection section: Int) -> Int
// ********************************************************************
{
return tablo.count
}
// ********************************************************************
func collectionView(collectionView: UICollectionView?, cellForItemAtIndexPath indexPath: NSIndexPath?) -> UICollectionViewCell?
// ********************************************************************
{
let cell = collectionView?.dequeueReusableCellWithReuseIdentifier("uneCellule", forIndexPath: indexPath) as CellulePersoCV
// Configuration de la cellule
cell.c1.text = String(itemCourant)
cell.c2.text = String(indexPath!.row)
cell.c3.text = tablo[indexPath!.row]
return cell
}
let DUREE_ANIMATION = 1 as NSTimeInterval
let ANIMATION_NB_FOIS = 3
var tabloImages = UIImage[]()
for i in 1...28 {
tabloImages.append(UIImage(named:"warrior_walk_\(i).png"))
}
// Renseigner l'image à partir du tableau et démarrer l'animation
uneImageAnimee.animationImages = tabloImages
uneImageAnimee.animationRepeatCount = ANIMATION_NB_FOIS
uneImageAnimee.animationDuration = DUREE_ANIMATION
uneImageAnimee.startAnimating()
// Créer un UIImage à partir du WEB
// Solution bloquante
// ** Solution 1: Forme courte
let uneURL:NSURL = NSURL(string:"http://hmp.me/dtm")
uneImageURL.image = UIImage(data:NSData(contentsOfURL:uneURL));
// ** Solution 2: Forme longue avec validation
let uneURL:NSURL = NSURL(string:"http://hmp.me/dtm")
var err:NSError?
let htmlData = NSData.dataWithContentsOfURL(uneURL, options: NSDataReadingOptions.DataReadingMappedIfSafe, error: &err)
uneImageURL.image = UIImage(data:htmlData)
// ** Solution 3 - non bloquante
let uneURL:NSURL = NSURL(string:"http://hmp.me/dtm")
let request:NSURLRequest = NSURLRequest(URL:uneURL)
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
self.uneImageURL.image = UIImage(data:data)
})
// Obtenir la météo de Montréal via l'API Yahoo
let urlString = "http://query.yahooapis.com/v1/public/yql?q=select%20item%20from%20weather.forecast%20where%20location%3D%22CAXX0301%22&format=json"
let request:NSURLRequest = NSURLRequest(URL:NSURL(string: urlString))
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
var err: NSError?
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
if(err?) {
// Si erreur de conversion JSON alors afficher l'erreur
print("JSON Error (err!.localizedDescription)")
}
print("===> résultat JSON:\n\n \(jsonResult)")
})
// Lancée automatiquement avant une transition 'segue'
// -------------------------------------------------------------
// Exemple pour une sélection à partir d'un UITableView
// ********************************************************************
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!)
// ********************************************************************
{
// Pointer sur la scène de destination
let sceneDestination = segue.destinationViewController as ClasseSceneDestination
// sender -> pointe sur la cellule sélectionnée
let selectionCourante = self.unTableView.indexPathForCell(sender as UITableViewCell).row;
// Envoyer les informations à la scène de destination
sceneDestination.tablo = tablo
sceneDestination.itemCourant = selectionCourante
} // prepareForSegue
// -------------------------------------------------------------
// Exemple pour une sélection à partir d'un UICollectionView
var _selection = 0
// ********************************************************************
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!)
// ********************************************************************
{
// Pointer sur la scène de destination
let sceneDestination = segue.destinationViewController as Scene03
// indice cellule sélectionnée via shouldSelectItemAtIndexPath
let selectionCourante = _selection;
// Envoyer les informations de la sélection courante
sceneDestination.title = tablo[selectionCourante]
}
// ********************************************************************
func collectionView(collectionView: UICollectionView?, shouldSelectItemAtIndexPath indexPath: NSIndexPath?) -> Bool
// ********************************************************************
{
_selection = indexPath!.row
return true
}
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
self.tournerLaPage("page2")
}
// ****************************************************
func tournerLaPage(scene:String) {
print("Tourner la page à \(scene)")
performSegueWithIdentifier(scene, sender: self)
}
override func viewDidLoad() {
super.viewDidLoad()
Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(Intro.passerAuMenuPrincipal), userInfo: nil, repeats: false)
} // viewDidLoad()
func passerAuMenuPrincipal(){
performSegue(withIdentifier: "versMenuPrincipal", sender: self)
} // passerAuMenuPrincipal
// Nouvelle méthode proposée avec Swift
let alert = UIAlertController(title: "Title", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Button", style: UIAlertActionStyle.default, handler: nil))
// Patch temporaire pour Xcode 8b5; utilisation de 'DispatchQueue' pour exécuter le self.present()
DispatchQueue.main.async( execute: { self.present(alert, animated: true, completion: nil) } )
// Ancien méthode inspirée d'Objective-C
var alert2 = UIAlertView()
alert2.title = "Un titre"
alert2.message = "Un message"
alert2.addButtonWithTitle("ok")
alert2.show()
var uneView = UINib(nibName: "Magazine01", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as UIView // Pour ajouter à la scène courante: view.addSubview(uneView);
animerImage(self.uneImage)
// ****************************************
func animerObjet (objet:UIView){
UIView.animateWithDuration(
2,
animations: { objet.alpha = 0.5 },
completion: { finished in
objet.hidden = false }
) // UIView
UIView.animateWithDuration(
1,
delay:1,
options:UIViewAnimationOptions.CurveEaseIn,
animations: { objet.center.x = objet.center.x + 50},
completion: { _ in
// Code à exécuter lorsque animation terminée
// Par exemple, une autre animation.
}
) // UIView
} // animerImage
CGRect personnage = [[lePersonnage.layer presentationLayer]frame];
CGRect sousZone = CGRectInset(personnage, personnage.size.width/2,personnage.size.height/2 );
if (CGRectIntersectsRect(sousZone, unObjet.frame))
{
NSLog(@"Il y a eu collision entre le personnage et %@", unObjet.class);
}
view.insertSubview(uneView, atIndex: view.subviews.count - 1)
if let tt = jsonResult["query"]!["results"]!["channel"]!["item"]!["condition"]!["temp"]! as String!
{
print("Température actuelle pour Montréal: \(tt)")
}
var tablo = ["Bob", "Binne", "Tintin", "Milou", "Hadock", "Castafiore", "Allan", "Tounesol", "Alcazar", "Barnabé", "Baxter", "Bill","Bohlwinkel", "Cipaçalouvishni"]
// Pour ajouter un élément
tablo.append("Objectif Lune")
// Ou
tablo+="encore"
// Pour un NSArray
var tabloNSArray:NSMutableArray = ["Tintin", "et", "Milou"]
tabloNSArray.addObject("Coke en stock")
// Énumération des éléments d'un tableau
for item in tablo) {
print("Item: \(item)")
}
// Énumération des éléments d'un tableau avec indice
for (index, value) in enumerate(tablo) {
print("Item \(index + 1): \(value)")
}
var dictio = ["Nom":"Paul", "Age":22, "Titre":"Intégrateur", "Expérience":2] // Ajouter un élément dictio["Compagnie"] = "TIM" var dictio2:NSDictionary = ["Nom":"Paul", "Age":22, "Titre":"Intégrateur", "Expérience":2]
//Pour parcourir les éléments d'un dictionnaire
for(NSString * key in unDictionnaire){
NSLog(@"clé: %@, contenu: %@", key, unDictionnaire[key]);
}
// ******************************************
func obtenirHeure() -> String {
let unFormateurDeDate = NSDateFormatter()
unFormateurDeDate.dateFormat = "'Nous sommes 'EEEE' et il est 'hh:mm:ss";
unFormateurDeDate.locale = NSLocale(localeIdentifier: "en_US_POSIX")
return unFormateurDeDate.stringFromDate(NSDate())
} // obtenirHeure
print(obtenirHeure())
// Ou en ajoutant une nouvelle méthode à la Classe NSDate
extension NSDate
{
convenience
init(dateString:String) {
let dateStringFormatter = NSDateFormatter()
dateStringFormatter.dateFormat = "yyyy-MM-dd"
dateStringFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
let d = dateStringFormatter.dateFromString(dateString)
self.init(timeInterval:0, sinceDate:d)
}
}
// ********************************************************
func creerBouton(texte:String, action:String) -> UIButton {
let unBouton = UIButton.buttonWithType(UIButtonType.System) as UIButton
unBouton.frame = CGRectMake(100, 100, 100, 50)
unBouton.backgroundColor = UIColor(red: 45/255, green: 23/255, blue: 111/255, alpha: 1.0)
unBouton.setTitle(texte, forState: UIControlState.Normal)
unBouton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
unBouton.addTarget(self, action: Selector(action), forControlEvents: UIControlEvents.TouchUpInside)
return unBouton
} // creerBouton
// ********************************************************
func boutonAction(sender:UIButton!)
{
print("Action du bouton maison!")
}
// Utilisation
self.view.addSubview(creerBouton("Victoire!", action: "boutonAction:"))
var imageFinale = UIImage()
func sauvegarderEcran(){
// Description : méthode servant à capturer l’écran et au besoin,
// en faire une sauvegarde dans l’album photos.
// Cacher le menu
leMenu!.isHidden = true
// 1 - Préparer un contexte de dessin à partir de la taille de la scène
UIGraphicsBeginImageContext(self.view.bounds.size);
// 2 – Dessiner à partir du claque par défaut de la scène
self.view.layer.render(in: UIGraphicsGetCurrentContext()!);
// 3 – Stocker le résultat dans notre objet local
imageFinale = UIGraphicsGetImageFromCurrentImageContext()!;
// 5 – Fermer le contexte de dessin
UIGraphicsEndImageContext();
// 6 – Facultatif - Stocker une copie de la capture d’écran dans l’album photos
// Note: À partir de iOS 10: Info.plist doit contenir une clé 'NSPhotoLibraryUsageDescription' de type 'String' qui indique à l'utilisateur comment sera utilisé sa librairie de photos.
UIImageWriteToSavedPhotosAlbum(imageFinale, nil, nil, nil );
leMenu!.isHidden = false
} // sauvegarderEcran
import Social
func posterSurFacebook() {
// Les étapes pour utiliser ‘facebook’
// 1 - Tester si le service et les informations de connexion sont dispo
if SLComposeViewController.isAvailable(forServiceType: SLServiceTypeFacebook)
{
// 2 - Créer un feuille pour le 'post'
if let controleur = SLComposeViewController (forServiceType: SLServiceTypeFacebook) {
// 3 - Composer le message
controleur.setInitialText("Test avec Swift et Xcode");
self.present(controleur, animated: true, completion: nil);
// 4 - Ajouter une image - facultatif
controleur.add(imageFinale);
// 5 - Ajouter un lien - facultatif
controleur.add(NSURL(fileURLWithPath: "http://tim.cstj.qc.ca") as URL!);
// 6 - Présenter la fenêtre de confirmation à l'utilisateur
// self.present(controleur, animated: true, completion: nil); // Ne fonctionne pas pour fb sous Xcode 8B5
// Par contre, fonctionne pour twitter.
// Temporairement utiliser:
self.navigationController?.pushViewController(controleur, animated: true)
}
} // if Facebook
} // posterSurFacebook
import Social
func posterSurTwitter() {
// Les étapes pour utiliser ‘twitter’
// 1 - Tester si le service et les informations de connexion sont dispo
// let sl = SLComposeViewController(for)
if SLComposeViewController.isAvailable(forServiceType: SLServiceTypeTwitter)
{
// 2 - Créer un feuille pour le 'post'
if let tweetSheet = SLComposeViewController (forServiceType: SLServiceTypeTwitter) {
// 3 - Composer le message
tweetSheet.setInitialText("CSTJ.TIM - Production sur support 2017. Introduction à Xcode 9 #CSTJ");
// 4 - Ajouter une image - facultatif
tweetSheet.add(imageFinale);
// 5 - Ajouter un lien - facultatif
//tweetSheet.add(NSURL(File:"http://tim.cstj.qc.ca"));
// 6 - Présenter la fenêtre de confirmation à l'utilisateur
self.present(tweetSheet, animated: true, completion: nil);
}
} // if twitter disponible ...
} // posterSurTwitter
// Note: il faut aussi renseigner le 'delegate' de l'objet
func textFieldShouldReturn(textField:UITextField!) -> Bool{
textField.resignFirstResponder()
return true
}
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var unChamp: UITextField!
var nbRetours = 0
override func viewDidLoad() {
super.viewDidLoad()
unChamp.delegate = self
} // viewDidLoad
/// Programmer une délégation
func textFieldShouldReturn(textField: UITextField!) -> Bool {
print("La touche 'Return' a été appuyée \(++nbRetours) fois.")
return true
} //textFieldShouldReturn
} // ViewController
# À partir de l'app 'terminal', naviguer vers le dossier parent du projet et saisir les commandes suivantes: git init git add . git commit -m "Premier 'Commit'"
// AppDelegate.swift
// stub
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
return true
} // didFinishLaunchingWithOptions
func applicationWillResignActive(application: UIApplication) { }
func applicationDidEnterBackground(application: UIApplication) { }
func applicationWillEnterForeground(application: UIApplication) { }
func applicationDidBecomeActive(application: UIApplication) { }
func applicationWillTerminate(application: UIApplication) { }
} // class AppDelegate:
Étapes: 1 - Creer un 'repo' sur github avec un Readme et ignore 'swift' 2 - Creer le projet sous Xcode avec l'option 'git' 3 - Avec terminal, cd vers le dossier du projet taper: git init git remote add origin https://github.com/votre compte/le projet.git git pull origin master git add * git commit -m "commit de depart" 4 - dand Xcode, faire un push // Pour le deuxieme membre de l'équipe faire: Source control -> check out // gestion des conflitsAutomatically resolving git merge conflicts in Xcode’s project.pbxproj file// Pousser les 'tags' vers le remote: git push origin --tags
Ajouter une classe ou une structure au projet qui contient des propriétés statiques:
// Fichier Static.swift
struct Static {
static var i = 99
}
/// Exemple d'utilisation:
override func viewDidAppear(animated: Bool) {
Static.i = 123
print(Static.i)
}
Dans le cas du message d’erreur suivante, suite à la lecture de contenu à partir d’une URL externe,
App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app’s Info.plist file.
Il faut ajouter la clé suivante dans le fichier info.plist de votre projet;
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
// Exemple d'un vidéo stream à partir d'une URL
// Created by Alain on 16-11-25.
import UIKit
import MediaPlayer
import AVKit
class ViewController: UIViewController {
override func viewDidLoad() {
let url = URL(string: "http://jplayer.org/video/m4v/Big_Buck_Bunny_Trailer.m4v")!
// Note, si la vidéo est locale, il faut construire l'URL ainsi:
// let url = Bundle.main.url(forResource: "piano", withExtension: "m4v")!
let player = AVPlayer(url: url)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
playerViewController.view.frame = CGRect(x: 0, y: 0, width: 640, height: 480)
// Ou bien ceci pour ajuster la vidéo à sa view
playerViewController.view.frame = uneViewServantAAfficherLaVideo.bounds
self.view.addSubview(playerViewController.view)
// Facultatif, Ajouter le panneau de control de la vidéo
self.addChildViewController(playerViewController)
player.play()
} // viewDidLoad
} // ViewController
/// **************************************************
/// Ou bien à partir d'un AVPlayerViewControler
/// Note: La vidéo occupera 100% de l'espace de la vue
import UIKit
import MediaPlayer
import AVKit
class MyPlayer: AVPlayerViewController {
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "http://jplayer.org/video/m4v/Big_Buck_Bunny_Trailer.m4v")!
self.player = AVPlayer(url: url) //player
self.player?.play()
} // viewDidLoad
} // MyPlayer
Il y a un exemple complet ici
Étant donné l’URL: http://prof-tim.cstj.qc.ca/cours/xcode/sources/apitim.php?mode=rnd&quant=5&format=json
Étant donné les classes suivantes:
struct YahooFinance: Codable {
var query: Query
}
struct Query:Codable {
var count: Int
var created: String
var lang: String
var results: Results
}
struct Results:Codable {
var quote: Array<Quote>
}
struct Quote:Codable {
var Symbol: String
var Ask: Float?
}
Chargement des données:
extension ViewController {
//MARK:- Obtenir les données
// =======================================================
func obtenirLaCitationDuJour(){
let uneURL = "http://prof-tim.cstj.qc.ca/cours/xcode/sources/apitim.php?mode=rnd&quant=5&format=json"
if let _data = NSData(contentsOf: URL(string: uneURL)!) as Data? {
// Note: Class.self veut dire "de type Class"
let données = try! JSONDecoder().decode(Citation.self, from: _data)
print(données)
for contenu in données.resultat {
// Note: ?? est le 'nil-coalescing operator'
let auteur = contenu.pensee_auteur ?? "Erreur: Nom de l'auteur non disponible"
let pensée = contenu.pensee_texte ?? "Erreur: Pensée de l'auteur non disponible"
print ("\(auteur) a dit:\n\t \(pensée)\n\n")
}
} // if let
} // obtenirLaCitationDuJour()
}
let tabeauItems = try! JSONDecoder().decode(Array<Item>.self,
from: jsonData)
À partir du terminal,
Dans le dossier du projet:
git config --global alias.ignore '!gi() { curl -L -s https://www.gitignore.io/api/$@ ;}; gi'
git ignore swift,macos >.gitignore
git add .gitignore
git commit -m "Ajout du fichier .gitignore"
https://github.com/ve2cuy/APIRiotGame-LeagueOfLegends
https://github.com/ve2cuy/LesAmiesDeLaScienceAvecFavoris