so i have already made a function here is it and how it work :
@IBAction func ValidButton(_ sender: Any) {
if(verif(){
//do some stuff
}print("it pass throught")
}
verif() -> Bool {
bool = true
//do some stuff and make my bool false
var lat1 = 0.00
var lat2 = 0.00
var long1 = 0.00
var long2 = 0.00
// where i call my function
getLatLongFromAddress(withAddress: address1) { (lat,long) in
lat1 = lat
long1 = long
print("when i call it : lat1 : ",lat1," long1 : ",long1)
}
getLatLongFromAddress(withAddress: address2) { (lat,long) in
lat2 = lat
long2 = long
print("when i call it : lat1 : ",lat2," long1 : ",long2)
}
//do some stuff
return bool
}
func getLatLongFromAddress(withAddress address: String, completionHandler: @escaping (CLLocationDegrees,CLLocationDegrees) -> Void) {
let geocoder = CLGeocoder()
// Use CLGeocoder to convert the address into coordinates
geocoder.geocodeAddressString(address) { (placemarks, error) in
// Return early if there was an error
guard error == nil else {
return
}
// Return early if no placemarks were found
guard let placemarks = placemarks, !placemarks.isEmpty else {
return
}
// Use the first placemark to obtain the coordinates
let location = placemarks.first!.location
let lat = location!.coordinate.latitude
let long = location!.coordinate.longitude
print("lat : ",lat)
print("long : ",long)
completionHandler(lat,long)
}
}
here is the log :
it pass throught
lat : 43.5982309
long : 1.4313821
when i call it : lat1 : 43.5982309 long1 : 1.4313821
lat : 43.6044242
long : 1.4437472
when i call it : lat1 : 43.6044242 long1 : 1.4437472
default
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
Hi so my function getLatFromAddress() is asynchronous and i need it run normally.
func getLatFromAddress(withAddress address: String, completionHandler: @escaping (Double) -> Void) {
let geocoder = CLGeocoder()
// Use CLGeocoder to convert the address into coordinates
geocoder.geocodeAddressString(address) { (placemarks, error) in
// Return early if there was an error
guard error == nil else {
return
}
// Return early if no placemarks were found
guard let placemarks = placemarks, !placemarks.isEmpty else {
return
}
// Use the first placemark to obtain the coordinates
let location = placemarks.first!.location
print("lat : ",location!.coordinate.latitude)
completionHandler(location!.coordinate.latitude)
}
}
how i use it :
lat1 = 0.00
getLat(withAddress: address1) { (result) in
lat1 = result
}
print("lat outFunc = ",lat1)
log :
lat outFunc = 0.00
lat : 43.6044242
so i've already coded a lot of time on swift and i would like to have your opinion.
I really think that to succeed in making a responsive application without shooting a bullet is a feat because either we try to use "DeviceLayout" and we have to make the application for all types of devices or we use autoLayout with the storyboard or each new view, each new constraint there is a problem that appears.
I know it's technically possible to design directly on the view controller but is it possible to make a view (header, content with scrollView, footer) only in the view controller ? because I spent 8 hours to put a scrollview with a footer and it's still not responsive
Hi,
so i am using a CLGeocoder() and i got a async problem and i don't know how to repair because i in my function i need to return a bool value. but in the log we can clearly see the asynchrone in the log .
how can i fix it ? i already many many different way to get lat and long from address but all of them got the asychrone problem because is still very similar to my code .
if i put my return in mygeocoder "i got Unexpected non-void return value in void function" how can i "synchrone" my code ?
Here is my code:
//getLongFromAddress is exactely the same
func getLatFromAddress(`let` address:String) -> Double {
let geocoder = CLGeocoder()
var lat = 0.00
geocoder.geocodeAddressString(address) { placemarks, error in
let placemark = placemarks?.first
if placemark?.location?.coordinate.latitude != nil {
lat = (placemark?.location?.coordinate.latitude)!
}else {
//print(error as Any)
}
//Here i get my lat
print("Lat: \(lat)")
}
//here my late is still 0.00
return lat
}
Where I call my function:
func checkAddress() -> Bool {
var check = true
var lat1 = 0.00
var long1 = 0.00
var lat2 = 0.00
var long2 = 0.00
address1 = "Paris"
address2 = "London"
lat1 = getLatFromAddress(let: address1)
long1 = getLongFromAddress(let: address1)
lat2 = getLatFromAddress(let: address2)
long2 = getLongFromAddress(let: address2)
print(lat1," - ",long1)
print(lat2," - ",long2)
let coordinate₀ = CLLocation(latitude: lat1, longitude: long1)
let coordinate₁ = CLLocation(latitude: lat2, longitude: long2)
//get the distance to meter and with meterToKiloleter convert meter into kilometer
let distance = meterToKilometer(let:coordinate₀.distance(from: coordinate₁))
if distance > 50 {
check = false
}
return check
}
Here is the log:
0.0 - 0.0
0.0 - 0.0
2022-12-02 18:46:06.936965+0100 Storyboard[10796:272148] [Client] {"msg":"#NullIsland Received a latitude or longitude from getLocationForBundleID that was exactly zero", "latIsZero":0, "lonIsZero":0, "location":'50 67 46 6F 01 00 00 00'}
2022-12-02 18:46:06.938224+0100 Storyboard[10796:272266] [Client] {"msg":"#NullIsland Received a latitude or longitude from getLocationForBundleID that was exactly zero", "latIsZero":0, "lonIsZero":0, "location":'50 27 4F 6F 01 00 00 00'}
2022-12-02 18:46:06.939091+0100 Storyboard[10796:272156] [Client] {"msg":"#NullIsland Received a latitude or longitude from getLocationForBundleID that was exactly zero", "latIsZero":0, "lonIsZero":0, "location":'50 E7 7A 6F 01 00 00 00'}
2022-12-02 18:46:06.939753+0100 Storyboard[10796:272501] [Client] {"msg":"#NullIsland Received a latitude or longitude from getLocationForBundleID that was exactly zero", "latIsZero":0, "lonIsZero":0, "location":'50 E7 57 6F 01 00 00 00'}
Lat: 48.8567879
Long: -0.0793965
Lat: 51.5033466
Long: 2.3510768
Hi so i struggle with my collection View i try to follow this tuto :
https://zeyad-elassal.medium.com/make-automatic-image-slider-in-ios-770ea1c28109 "canno't make a link because this URL is not a permit domain on this forum sorry"
and in the extension i have a bug appear
extension HomeClientViewController: UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
var cell = SliderHomeClient.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? SliderCollectionViewCellHomeClient
cell?.imageSliderHomeClient.image = sliderImage[indexPath.row]
return cell ?? <#default value#>
}
func collectionView(_ collectionView:UICollectionView, numberOfItemsInSection section: Int) -> Int {
return sliderImage.count
}
}
i have one error appear :
The "imageSliderHomeClient" outlet from the HomeClient to the UIView is invalid. Outlets cannot be connected to repeating content.
but i have also see the collection View change here in the tuto was :
CollectionView -> CollectionViewCell -> imageView
And mine was CollectionView -> CollecitonViewCell -> ContentView -> imageView
so i try to delete the image View and rename my contentView as the same as my imageView and remove image.
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
var cell = SliderHomeClient.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? SliderCollectionViewCellHomeClient
//HERE is different
cell?.imageSliderHomeClient = sliderImage[indexPath.row]
//HERE is different
return cell ?? <#default value#>
}
func collectionView(_ collectionView:UICollectionView, numberOfItemsInSection section: Int) -> Int {
return sliderImage.count
}
}
but i have another error appear :
Cannot assign value of type 'UIImage?' to type 'UIView?'
how can i fix these to make my collectionView plz
i put here my whole code if :
import UIKit
import Alamofire
import SwiftUI
class HomeClientViewController: UIViewController {
@IBOutlet weak var dotHomeClient: UIPageControl!
@IBOutlet weak var SliderHomeClient: UICollectionView!
var email: String?
let sliderImage = [UIImage(named: "slide1"),
UIImage(named: "slide2"),
UIImage(named: "slide3"),
UIImage(named: "slide4")]
var timer = Timer()
var counter = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
sliderHomeClient()
}
func sliderHomeClient(){
dotHomeClient.numberOfPages = sliderImage.count
dotHomeClient.currentPage = 0
DispatchQueue.main.async {
self.timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.changeImage), userInfo: nil, repeats: true)
}
}
@objc func changeImage() {
if counter < sliderImage.count {
let index = IndexPath.init(item: counter, section: 0)
self.SliderHomeClient.scrollToItem(at: index, at: .centeredHorizontally, animated: true)
dotHomeClient.currentPage = counter
counter += 1
} else {
counter = 0
let index = IndexPath.init(item: counter, section: 0)
self.SliderHomeClient.scrollToItem(at: index, at: .centeredHorizontally, animated: false)
dotHomeClient.currentPage = counter
counter = 1
}
}
}
extension HomeClientViewController: UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
var cell = SliderHomeClient.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? SliderCollectionViewCellHomeClient
cell?.imageSliderHomeClient = sliderImage[indexPath.row]
return cell ?? <#default value#>
}
func collectionView(_ collectionView:UICollectionView, numberOfItemsInSection section: Int) -> Int {
return sliderImage.count
}
//different class
class SliderCollectionViewCellHomeClient: UICollectionViewCell {
@IBOutlet weak var imageSliderHomeClient2: UIImageView!
@IBOutlet weak var imageSliderHomeClient: UIView!
}
Hi so i have some probleme to send some parameters to my php.
when my php don't take post :
<?php
require_once "connIOS.php";
require_once "validate.php";
$email =validate($_POST['id']);
$mdp = validate($_POST['password']);
$sql = 'SELECT `Cl_Email`,`Cl_mdp` FROM `clients` WHERE `email`="myemail@gmail.com" AND `password`= "1234"';
// Check if there are results
if ($result = mysqli_query($con, $sql))
{
// If so, then create a results array and a temporary one
// to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
while($row = $result->fetch_object())
{
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Finally, encode the array to JSON and output the results
echo json_encode($resultArray);
}
// Close connections
mysqli_close($con);
?>
i get in my swift log :
[{"email":"myemail@gmail.com","password":"1234"}]
but i get nothing when my request SQL take the post
here is my swiftcode :
import UIKit
import Alamofire
class ViewController: UIViewController {
@IBOutlet weak var idTextField: UITextField!
@IBOutlet weak var passwordTextField:UITextField!
@IBAction func forgotPasswordButton(_ sender: UIButton) {
}
@IBAction func loginButton(_ sender: UIButton) {
var id:NSString = idTextField.text! as NSString
var password:NSString = passwordTextField.text! as NSString
var urlLink = "http://domain.com/myPHP.php"
if(id.isEqual(to:"") || password.isEqual(to: "")){
print("id ou mdp vide")
let alert = UIAlertController(title: "", message: "identifiant ou mot de passe incorrecte", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
switch action.style {
case .default:
print("default")
case .cancel:
print("cancel")
case .destructive:
print("destructive")
@unknown default:
fatalError()
}
}))
self.present(alert, animated: true, completion: nil)
}else{
print("reussite")
let parameters = ["id":"\(id)","password":"\(password)"]
var sParams = ""
for (key,value) in parameters{
//http://domain.com/Appli/myPHP.php ? parameter1Key = parameter1Value & parameter2Key = parameter2Value
sParams += key + "=" + (value as String) + "&"
print("\(key),\(value as String)")
}
if !sParams.isEmpty{
sParams = "?" + sParams
if sParams.hasSuffix("&"){
sParams.removeLast()
}
urlLink = urlLink + sParams
}else{
print("!sParams.isEmpty fail")
}
let serializer = DataResponseSerializer(emptyResponseCodes: [200,204,205])
var request = URLRequest(url : URL(string:urlLink)!)
AF.request(request).uploadProgress{progress in }.response(responseSerializer: serializer){ response in
if response.error == nil {
var responseString: String!
responseString = ""
if response.data != nil {
responseString = String(bytes:response.data!, encoding: .utf8)
}else{
responseString = response.response?.description
}
print(responseString ?? "")
print(response.response?.statusCode as Any)
var data : NSData!
if let data = data {
//Succeed
let dataLength = data.length
print("Size: \(dataLength) Bytes")
}else{
//print(data)
}
print("response time: \(response.metrics?.taskInterval.duration ?? 0)")
}
}
}
}
@IBAction func signInButton(_ sender: UIButton) {
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
Hello, I have a problem when I launch the application I have this error displayed in the log of the swift:
Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not have any content around line 2, column 0." UserInfo={NSDebugDescription=JSON text did not have any content around line 2, column 0., NSJSONSerializationErrorIndex=1}
here is the php :
<?php
$hote="myHost";
$login="myLogin";
$mdp="myPassword";
$nomdb="nameDB";
// Create connection
$con= mysqli_connect($hote,$login,$mdp,$nomdb);
$con->set_charset("utf8mb4");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// This SQL statement selects ALL from the table 'Locations'
$sql = "SELECT `id`,`nom`,`prenom`,`tel`,`email`,`mdp`,`adr`,`cp`,`ville` FROM clients";
// Check if there are results
if ($result = mysqli_query($con, $sql))
{
// If so, then create a results array and a temporary one
// to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
while($row = $result->fetch_object())
{
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Finally, encode the array to JSON and output the results
echo utf8_encode($resultArray);
}
// Close connections
mysqli_close($con);
?>
With some research I know that this error is due to a json data received from the server (I don't know the exact term sorry)
but unfortunately finding the error and solving it are two different things could help me to solve it ?
so i start to make an app and i try so I started an application that allows to make a connection to a database.
and i have also 2 signal SIGABRT error i put where the error spawn in my code.
I met some errors and unfortunately I don't know how to fix it here is the log:
2022-11-08 18:27:45.563127+0100 test[19072:332743] [SceneConfiguration] Info.plist configuration "Default Configuration" for UIWindowSceneSessionRoleApplication contained UISceneClassName key, but could not load class with name "".
2022-11-08 18:27:45.563460+0100 test[19072:332743] [SceneConfiguration] Info.plist configuration "(no name)" for UIWindowSceneSessionRoleApplication contained UISceneClassName key, but could not load class with name "".
2022-11-08 18:27:45.564063+0100 test[19072:332743] [SceneConfiguration] Info.plist configuration "Default Configuration" for UIWindowSceneSessionRoleApplication contained UISceneClassName key, but could not load class with name "".
Could not cast value of type 'NSNull' (0x1b7cc9a28) to 'NSString' (0x1b7cc7ec8).
2022-11-08 18:27:45.631625+0100 test[19072:332954] Could not cast value of type 'NSNull' (0x1b7cc9a28) to 'NSString' (0x1b7cc7ec8).
Could not cast value of type 'NSNull' (0x1b7cc9a28) to 'NSString' (0x1b7cc7ec8).
CoreSimulator 857.13 - Device: iPhone 14 Pro (6E6732CE-5770-4803-96B8-07D2C8BBAF0E) - Runtime: iOS 16.1 (20B72) - DeviceType: iPhone 14 Pro
here is my homeModel :
import Foundation
import UIKit
protocol HomeModelDelegate {
func itemsDowloaded(client:[Client] )
}
class HomeModel : NSObject {
var delegate:HomeModelDelegate?
func getItems(){
//Hit the conn url
let serviceURL = "http://localhost/service.php"
//Download the JSON Data
let url = URL(string: serviceURL)
if let url = url {
// Create a URL Session
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url) { (data, url, error) in
if error == nil {
//Succed
//call the parseJson
//signal SIGABRT
self.parseJson(data!)
}else{
//error
}
}
// Start the task
task.resume()
}
//notify the view controller and pass the data back
}
func parseJson(_ data:Data){
var clientArray = [Client] //() can't put () because error on the post
do {
//Parse the data into Client object
let jsonArray = try JSONSerialization.jsonObject(with: data, options: []) as! [Any]
//loop through each result in the json array
for jsonResult in jsonArray {
//Cast json result as a dictionary
//signal SIGABRT
let jsonDict = jsonResult as! [String:String]
//Create a new client and set properties
let cli = Client(id:jsonDict["id"]!,
lastName: jsonDict["nom"]!,
firstName: jsonDict["prenom"]!,
email: jsonDict["email"]!,
mdp: jsonDict["mdp"]!)
clientArray.append(cli)
}
// Pass the client array back to delegation
delegate?.itemsDowloaded(client: clientArray)
}
catch{
print("error parseJson")
}
}
}