Post

Replies

Boosts

Views

Activity

Reply to how can i make my async func wait
i try it with another way to do it because my task still didn't work so how i did it is :   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 : lat2 : ",lat2," long2 : ",long2)           //do my stuff       }       } i totally change my whole code it become ugly but atleast it work im really thanksfull to you @Scott and @Claude31 i learn a lot about Async i didn't know about that
Topic: Programming Languages SubTopic: Swift Tags:
Jan ’23
Reply to how can i make my async func wait
@IBAction func validButton(_ sender: Any) {     Task { @MainActor in       if verif() {   let date = universalDate         let address = self.addressEditTextClient.text         let cp = self.cpEditTextClient.text         let city = self.villeEditTextClient.text         let accessibilite = self.villeEditTextClient.text         let type_chantier = self.typeChantierEditTextClient.text         let email = email                   var urlLink = "my link"                   //dateFormat                   let parameters = [my parameter]               var sParams = ""                   for (key,value) in parameters{           //domain.com?parameter1Key=parameter1Value&parameter2Key=parameter2Value           sParams += key + "=" + (value) + "&"           print("\(key),\(value)")                     }         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])                   let urlString = urlLink.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! //This will fill the spaces with the %20                   //API         let request = URLRequest(url : URL(string:urlString)!)         AF.request(request).uploadProgress{progress in }.response(responseSerializer: serializer){ [self] response in           if response.error == nil {             var responseString: String!                           responseString = ""                           if response.data != nil {               //receive data-->responseString and put into dataJson               responseString = String(bytes:response.data!, encoding: .utf8)               var dataJson = responseString               //remove [ ] on the dataJson               dataJson = dataJson!.replacingOccurrences(of: "[", with: "")               dataJson = dataJson!.replacingOccurrences(of: "]", with: "")                               let jsonObjectData = dataJson!.data(using: .utf8)!               let data = try? JSONDecoder().decode(                 Data.self,                 from: jsonObjectData               )               print(data?.result as Any)             }else{               responseString = response.response?.description             }             print("response time: \(response.metrics?.taskInterval.duration ?? 0)")           }         }       }       else{         print("it pass through")       }     }   } here is verif :   func verif() -> Bool {     var check = true;     textBlanc()           var message = "Attention : \n";           if !checkIssetEditText() {       message += " - il faut remplir tous les champs pour valider";       check = false;     } else {       let address1 = makeAddress(let: self.addressEditTextClient.text!,                     let: self.cpEditTextClient.text!,                     let: self.villeEditTextClient.text!)       let address2 = makeAddress(let: "Toulouse",                     let: "",                     let: "")       var lat1 = 0.00       var lat2 = 0.00       var long1 = 0.00       var long2 = 0.00                     Task {         do {           let coordinates = try await getLatLongFromAddress(withAddress: address1)           lat1 = coordinates.latitude           long1 = coordinates.longitude           print("when i call it : lat1 : ",lat1," long1 : ",long1)         } catch {           print(error)         }                   do {           let coordinates = try await getLatLongFromAddress(withAddress: address2)           lat2 = coordinates.latitude           long2 = coordinates.longitude           print("when i call it : lat1 : ",lat1," long1 : ",long1)         } catch {           print(error)         }       }                          print(" lat1 : ", lat1," long1 : ",long1)       print(" lat2 : ",lat2," long2 : ",long2)               if !checkCP(let: self.cpEditTextClient.text!){                   cpEditTextClient.textColor = .yellow                   message += " - le code postal est incorrect \n"         check = false       } else if !checkAddress(let: lat1, let: lat2, let: long1, let: long2, let : 55.0){                   addressEditTextClient.textColor = .yellow         cpEditTextClient.textColor = .yellow         villeEditTextClient.textColor = .yellow                   message += " - les livraisons ne peuvent aller au-delà de 50 km de la ville \n"         check = false       }     }           if !check {       let alert = messageAlerte(let: message,let:"")       self.present(alert, animated: true, completion: nil)     }     print("end")     return check         } and my function and log is still the same i just remove my url and my parameter from my button
Topic: Programming Languages SubTopic: Swift Tags:
Jan ’23
Reply to how can i make my async func wait
@IBAction func ValidButton(_ sender: Any) {     Task { @MainActor in       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             Task {         do {           let coordinates = try await getLatLongFromAddress(withAddress: address1)           lat1 = coordinates.latitude           long1 = coordinates.longitude           print("when i call it : lat1 : ",lat1," long1 : ",long1)         } catch {           print(error)         }                   do {           let coordinates = try await getLatLongFromAddress(withAddress: address2)           lat2 = coordinates.latitude           long2 = coordinates.longitude           print("when i call it : lat1 : ",lat1," long1 : ",long1)         } catch {           print(error)         }       }       print(" lat1 : ", lat1," long1 : ",long1)       print(" lat2 : ",lat2," long2 : ",long2) //do some stuff return bool } //myfunction func getLatLongFromAddress(withAddress address: String) async throws -> CLLocationCoordinate2D {  let geocoder = CLGeocoder()       let placemarks = try await geocoder.geocodeAddressString(address)           let location = placemarks[0].location // for now we’ll assume [0] always exists       let result = location!.coordinate          return result // for now we’ll assume the coordinate always exists } here is the log :  lat1 : 0.0 long1 : 0.0  lat2 : 0.0 long2 : 0.0 2023-01-02 16:32:36.503786+0100 myApp[8758:254961] [Client] {"msg":"#NullIsland Received a latitude or longitude from getLocationForBundleID that was exactly zero", "latIsZero":0, "lonIsZero":0, "location":'80 B6 C8 08 03 00 00 00'} end it pass through when i call it : lat1 : 43.5982309 long1 : 1.4313821 2023-01-02 16:32:36.554774+0100 myApp[8758:254659] [Client] {"msg":"#NullIsland Received a latitude or longitude from getLocationForBundleID that was exactly zero", "latIsZero":0, "lonIsZero":0, "location":'80 36 D1 08 03 00 00 00'} when i call it : lat1 : 43.5982309 long1 : 1.4313821 default
Topic: Programming Languages SubTopic: Swift Tags:
Jan ’23
Reply to how can i make my async func wait
here is the log : Selected value 2023-01-02 14:59:30 +0000  lat1 : 0.0 long1 : 0.0  lat2 : 0.0 long2 : 0.0 2023-01-02 15:59:31.688751+0100 myApp[8046:225025] [Client] {"msg":"#NullIsland Received a latitude or longitude from getLocationForBundleID that was exactly zero", "latIsZero":0, "lonIsZero":0, "location":'80 F6 1C 0A 03 00 00 00'} end it pass through when i call it : lat1 : 43.5982309 long1 : 1.4313821 2023-01-02 15:59:31.834854+0100 myApp[8046:225025] [Client] {"msg":"#NullIsland Received a latitude or longitude from getLocationForBundleID that was exactly zero", "latIsZero":0, "lonIsZero":0, "location":'80 F6 1C 0A 03 00 00 00'} when i call it : lat2 : 43.6044242 long2 : 1.4437472
Topic: Programming Languages SubTopic: Swift Tags:
Jan ’23
Reply to how can i make my async func wait
it still don't work i don't know to do now ... my task :    Task {         do {           let coordinates = try await getLatLongFromAddress(withAddress: address1)           lat1 = coordinates.latitude           long1 = coordinates.longitude           print("when i call it : lat1 : ",lat1," long1 : ",long1)         } catch {           print(error)         }                   do {           let coordinates = try await getLatLongFromAddress(withAddress: address2)           lat2 = coordinates.latitude           long2 = coordinates.longitude           print("when i call it : lat1 : ",lat1," long1 : ",long1)         } catch {           print(error)         }       } my function : func getLatLongFromAddress(withAddress address: String) async throws -> CLLocationCoordinate2D {  let geocoder = CLGeocoder()       let placemarks = try await geocoder.geocodeAddressString(address)           let location = placemarks[0].location // for now we’ll assume [0] always exists       let result = location!.coordinate          return result // for now we’ll assume the coordinate always exists }
Topic: Programming Languages SubTopic: Swift Tags:
Jan ’23
Reply to cancel the async and make it run normally
"Your other post mentions you have an equivalent getLongFromAddress method. That’s not a good idea if you actually need both coordinates, since both call geocodeAddressFromString which is async and relatively slow. Instead you should have a single (say) getLocationFromAddress to get both the latitude and longitude together. If in any any specific call you need only one of them, then that’s fine." thx you @Claude31@Scott for yours respond and just below i make my function get the lat and the long at same time. i have another question can you help me to make my function to transform into a async await plz or send me a good tuto 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)   } } on my main :        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         lat1 = lat         long1 = long         print("when i call it : lat1 : ",lat2," long1 : ",long2)       }
Topic: Programming Languages SubTopic: Swift Tags:
Dec ’22
Reply to can't complete my collection View
désolée pour la réponse lente j'étais très occupé la semaine dernière. alors j'ai également un peu modifié mon code mais dans l'ensemble c'est exactement le même avec le même problème . j'ai réduit le nombre d'erreur a un mais c'est toujours celui qui me pose probleme : imageCustomSliderHomeClient outlet from the HomeClient to the UIImageView is invalid. Outlets cannot be connected to repeating content. cmd click sur mon image j'ai rien qui apparait par contre j'ai son outlet donc je vais le posté. je rajoute mon mail dans le post quand j'ai une réponse
Topic: Programming Languages SubTopic: Swift Tags:
Nov ’22
Reply to can't complete my collection View
here is my storyboard and i can't delete Content View if i want to delete my Content View i need to destroy my cell "SliderCollectionViewCellHomeClient" here is the the error : //different class class SliderCollectionViewCellHomeClient: UICollectionViewCell {   @IBOutlet weak var imageSliderHomeClient: UIImageView! } and i wasn't sure about how to show my connections in sotryboard but its the log right ? 2022-11-18 16:53:13.662034+0100 batigreenStoryboard[8572:197889] [Storyboard] Unknown class HomeClient in Interface Builder file. 2022-11-18 16:53:13.691509+0100 batigreenStoryboard[8572:197889] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<UIView 0x148d686c0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key imageSliderHomeClient.' *** First throw call stack: ( 0  CoreFoundation           0x000000018040e7ec __exceptionPreprocess + 172 1  libobjc.A.dylib           0x0000000180051144 objc_exception_throw + 56 2  CoreFoundation           0x000000018040e4fc -[NSException init] + 0 3  Foundation             0x0000000180b5205c -[NSObject(NSKeyValueCoding) setValue:forKey:] + 308 4  UIKitCore              0x0000000102499284 -[UIView(CALayerDelegate) setValue:forKey:] + 156 5  UIKitCore              0x0000000101c7c984 -[UIRuntimeOutletConnection connect] + 80 6  CoreFoundation           0x00000001803f8994 -[NSArray makeObjectsPerformSelector:] + 192 7  UIKitCore              0x0000000101c7478c -[UINib instantiateWithOwner:options:] + 1408 8  UIKitCore              0x000000010197a028 -[UIViewController loadView] + 392 9  UIKitCore              0x000000010197a2b0 -[UIViewController loadViewIfRequired] + 96 10 UIKitCore              0x000000010197a800 -[UIViewController view] + 20 11 UIKitCore              0x00000001018d2618 -[UINavigationController _startCustomTransition:] + 916 12 UIKitCore              0x00000001018e3be8 -[UINavigationController _startDeferredTransitionIfNeeded:] + 492 13 UIKitCore              0x00000001018e4ab8 -[UINavigationController __viewWillLayoutSubviews] + 92 14 UIKitCore              0x00000001018cc2e0 -[UILayoutContainerView layoutSubviews] + 168 15 UIKitCore              0x0000000102499bc8 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1920 16 QuartzCore             0x0000000187f18844 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 440 17 QuartzCore             0x0000000187f232fc _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 128 18 QuartzCore             0x0000000187e51058 _ZN2CA7Context18commit_transactionEPNS_11TransactionEdPd + 452 19 QuartzCore             0x0000000187e7ce28 _ZN2CA11Transaction6commitEv + 652 20 QuartzCore             0x0000000187e7e25c _ZN2CA11Transaction25flush_as_runloop_observerEb + 68 21 CoreFoundation           0x000000018037217c __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 32 22 CoreFoundation           0x000000018036cb1c __CFRunLoopDoObservers + 512 23 CoreFoundation           0x000000018036cfd4 __CFRunLoopRun + 968 24 CoreFoundation           0x000000018036c7f4 CFRunLoopRunSpecific + 584 25 GraphicsServices          0x0000000188faec98 GSEventRunModal + 160 26 UIKitCore              0x00000001020005d4 -[UIApplication _run] + 868 27 UIKitCore              0x00000001020045cc UIApplicationMain + 124 28 libswiftUIKit.dylib         0x0000000101468fc0 $s5UIKit17UIApplicationMainys5Int32VAD_SpySpys4Int8VGGSgSSSgAJtF + 100 29 batigreenStoryboard         0x0000000100781ebc $sSo21UIApplicationDelegateP5UIKitE4mainyyFZ + 104 30 batigreenStoryboard         0x0000000100781e44 $s19batigreenStoryboard11AppDelegateC5$mainyyFZ + 44 31 batigreenStoryboard         0x0000000100781f40 main + 28 32 dyld                0x0000000100ad9fa0 start_sim + 20 33 ???                 0x00000001009ede50 0x0 + 4305378896 34 ???                 0x8e0a000000000000 0x0 + 10234993103152873472 ) libc++abi: terminating with uncaught exception of type NSException *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<UIView 0x148d686c0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key imageSliderHomeClient.' terminating with uncaught exception of type NSException CoreSimulator 857.13 - Device: iPhone 14 Pro (6E6732CE-5770-4803-96B8-07D2C8BBAF0E) - Runtime: iOS 16.1 (20B72) - DeviceType: iPhone 14 Pro
Topic: Programming Languages SubTopic: Swift Tags:
Nov ’22
Reply to Error Domain=NSCocoaErrorDomain Code=3840 AND
my bad i forgot my code : 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://myFTPSERVER/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 let data = data {           //Succed           print(data)             //call the parseJson           self.parseJson(data)         }else{                     }       }       // Start the task       task.resume()     }     //notify the view controller and pass the data back         }       func parseJson(_ data:Data){           var clientArray = [Client]()     do {       //Parse the data into Client structs       let jsonArray = try JSONSerialization.jsonObject(with: data, options: []) as! [Any]       print(jsonArray)               //loop through each result in the json array       for jsonResult in jsonArray {                   //Cast json result as a dictionary         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"]!,                  phone: jsonDict["tel"]!,                  mdp: jsonDict["mdp"]!,                  address: jsonDict["adr"]!,                  cp: jsonDict["cp"]!,                  city: jsonDict["ville"]!)                   clientArray.append(cli)       }               // Pass the client array back to delegation       delegate?.itemsDowloaded(client: clientArray)     }     catch{       print(error)     }   } } i also print my data i receive so here is the new log : 1 bytes 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}
Topic: Programming Languages SubTopic: Swift Tags:
Nov ’22