Posts

Showing posts with the label swift

SIGSEGV(Bad Memory Access) error while profiling in Instruments

SIGSEGV(Bad Memory Access) error while profiling in Instruments I'm trying to catch memory leak and retain cycles with Leak Profiler in Instruments tool. However, whenever I click the record button in Instruments, app looks like to start then crash. If I open the app from Xcode and transfer it to Instruments, App crash after I click any of the UIButton . If I open app from Simulator, I can get the second screen but then It also crashes. In addition, App doesn't show any leak in memory graph and also doesn't crash on normal usage. UIButton Here is the crash log; Exception Type: EXC_BAD_ACCESS (SIGSEGV) Exception Subtype: KERN_INVALID_ADDRESS at 0x0000000000000018 VM Region Info: 0x18 is not in any region. Bytes before following region: 4377985000 REGION TYPE START - END [ VSIZE] PRT/MAX SHRMOD REGION DETAIL UNUSED SPACE AT START ---> __TEXT 0000000104f2c000-0000000104fbc000 [ 576K] ...

Xcode/Swift: How to add extra argument to a bash execution

Xcode/Swift: How to add extra argument to a bash execution I have this Code: func syncShellExec(path: String?) { let script = [path!] let process = Process() let outputPipe = Pipe() let filelHandler = outputPipe.fileHandleForReading process.launchPath = "/bin/bash" process.arguments = script process.standardOutput = outputPipe . . . In Swift I call it this way: self.syncShellExec(path: Bundle.main.path(forResource: "initial", ofType: "command")) Now I want to add an Extra argument for the script itself (using Functions within the Bashscript). In Terminal it would be like this: /usr/bin/bash initial.command Do_My_Function How to add this to the process? 1 Answer 1 You can add a “variadic parameter” to your Swift function, and append the arguments to process.arguments : process.arguments...

Alamofire Multipart is not working in XCode 9.4.1

Alamofire Multipart is not working in XCode 9.4.1 When I've upgrade my XCode version to 9.4.1 , Alamofire Multipart is not working and I don't know why. It was completely working in previous XCode version. 9.4.1 Please let me know how to fix it. Thanks Alamofire.upload( multipartFormData: { multipartFormData in multipartFormData.append(self.imageFrontData, withName: "front-photo", fileName: "front-photo.png", mimeType: "image/png") multipartFormData.append(self.imageBackData, withName: "back-photo", fileName: "back-photo.png", mimeType: "image/png") for (key, value) in parameters { multipartFormData.append((value?.data(using: String.Encoding.utf8)!)!, withName: key) } }, usingThreshold: UInt64.init(), to: uploadURL!, method: .post, headers: headers) { (result) in switch result { case .success(let upload, _, _): upload.responseJSON { response in ...

OSX Swift open URL in default browser

OSX Swift open URL in default browser How to open a url in system default browser by using Swift as programming language and OSX as plattform. I found a lot with UIApplication like UIApplication.sharedApplication().openURL(NSURL(string: object.url)) but this works just on iOS and not on OSX And the Launch Services, I found has no examples for swift and there is a lot deprecated for OSX 10.10 Any help welcome - thanks. I guess it's because we're supposed to use the new Extensions instead... – Michele De Pascalis Nov 2 '14 at 22:31 I upvoted because I neede to know how to do that in iOS only xd – Josh Nov 12 '15 at 11:37 6 Answers ...

Unable to reload only the selected cell

Unable to reload only the selected cell I want to reload only the selected cell in particular when tapping a picture in a cell.But i got the error cannot convert value of type 'IndexPath.Type' to expected argument type 'IndexPath'in this line: loadPostsValue(indexPath: IndexPath) func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let indexPath = self.collectionView.indexPathsForSelectedItems print(indexPath) loadPostsValue(indexPath: IndexPath) } func loadPostsValue(indexPath: IndexPath) { posts.removeAll() let ref = Database.database().reference() ref.child("posts").observe(.childAdded) { (snapshot: DataSnapshot) in if let dict = snapshot.value as? [String: Any] { guard let titleText = dict["title"] as? String else{return} let locationDetails = dict["location"] as! String let capt...

Want to call method after firebase authentication is complete

Want to call method after firebase authentication is complete func signUpPressed(){ guard let email = signupview.emailTextField.textField.text, let password = signupview.passwordTextField1.textField.text, let name = signupview.nameTextField.textField.text else{ return } Auth.auth().createUser(withEmail: email, password: password, completion: {(User, error) in if error != nil{ print(error) return } let ref = Database.database().reference() let uid = User?.user.uid! let userReference = ref.child("Users").child((uid)!) let values = ["name": name, "email": email] userReference.updateChildValues(values, withCompletionBlock: {(err, ref) in if err != nil{ print(err) return } print("User saved to firebase") }) }) getUserInfo() } What I hope to achieve from this is t...

UIButtons and UITextViews not working in Scrollview

Image
UIButtons and UITextViews not working in Scrollview So I have a scrollview with a view inside. In this view I have several textviews and buttons. When I run the app, it will scroll, but I cannot click the buttons or insert text into the textviews. I have checked for multiple solutions online and have yet to find one. I have already allowed user interaction on everything. I have disabled the click delay. I am running out of ideas here. share code or better a demo of what you have tried – Sh_Khan Jun 30 at 23:06 Have you tried using the Debug View Hierarchy to check if there is something else blocking the textview and buttons? – mn1 Jun 30 at 23:28 please share your cod...

Why UIImageView when its content mode is .scaleAspectFill in portrait pictures goes over its constraints?

Image
Why UIImageView when its content mode is .scaleAspectFill in portrait pictures goes over its constraints? I'm creating an image gallery using ImageView and CollectionView. Everything is working fine but portrait mode pictures go over constraints. Why is that? myPicture = UIImageView(image: myArray[0]) view.addSubview(myPicture) myPicture.translatesAutoresizingMaskIntoConstraints = false myPicture.contentMode = .scaleAspectFill myPicture.topAnchor.constraint(equalTo: tabBar.bottomAnchor, constant: view.bounds.height / 80).isActive = true myPicture.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true myPicture.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true myPicture.bottomAnchor.constraint(equalTo: collectionView.topAnchor, constant: 0).isActive = true 1 Answer 1 You need to set myPicture.clipsToBounds = true ...

non-deterministic crashing behavior in app w/ custom frameworks

non-deterministic crashing behavior in app w/ custom frameworks I am working on an app that uses 4 frameworks i made. Its structured as a workspace and each framework has a project. This one framework that basically encapsulates some UIKit convenience functions keeps on crashing at this call site. containerView.pinTo(superView: hostView) . containerView.pinTo(superView: hostView) what happens is I build and run the app once. Then, for the second and remaining runs it crashes here. So its non-deterministic in that it works once, but never again. Here, both hostView and containerView are not nil. hostView containerView When problems occur at this level (frameworks, linking, etc.) I don't even know where to begin. I've embedded and linked the frameworks as best as I know. What is happening here? By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, priv...

Request failed: forbidden (403) after adding the provided url from Firebase in the callback settings of the Twitter app

Request failed: forbidden (403) after adding the provided url from Firebase in the callback settings of the Twitter app Adding this callback url in the settings, doesn't work with Firebase (doesn't show any user that signed up): [twitterkit-Consumer_ID://] Adding this callback url in the settings shows error "forbidden (403)": https://the-app-name.firebaseapp.com/__/auth/handler Everything in the info.plist was put correctly: consumer id, .... Everything in App Delegate was put correctly: Twitter.sharedInstance.start..., Twitter.sharedInstance.application... Help much appreciated By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

spaces on mail body when we Open gmail app from iOS url schemes

spaces on mail body when we Open gmail app from iOS url schemes Is it possible to provide spaces or new line or line breaks on gmail compose on URL schemes. I tried both /n or stringByAddingPercentEscapesUsingEncoding , but space or lines breaks are not reflecting. /n stringByAddingPercentEscapesUsingEncoding googlegmail:///co?subject=subject&body= "nnn textfirstname" googlegmail:///co?subject=subject&body= "nnn textfirstname" Use HTML email body and a <a href="googlegmail:....">Whateverntextnyounwant</a> . – rmaddy Jun 30 at 19:33 <a href="googlegmail:....">Whateverntextnyounwant</a> 1 Answer 1 This is not an issue with iOS or url-scheme. You need to use html tag to set new line. F...

Encoding base64 string to image in swift received from mysql

Encoding base64 string to image in swift received from mysql I am receiving a base64 string from mysql (stored as blob) and try to encode it like this: func loadImage() { var request = URLRequest(url: URL(string: URL_IMAGES)!) request.httpMethod = "POST" let userid = self.defaultValues.integer(forKey: "userid") let postString = "userid=(userid)" request.httpBody = postString.data(using: .utf8) let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { print("error=(String(describing: error))") return } if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { print("statusCode should be 200, but is (httpStatus.statusCode)") print("response = (String(describing: response))") } let responseString = String(data: data, encoding: .utf8)...

Rounding the height of a table cell in Swift

Rounding the height of a table cell in Swift I need to calculate the cell height of the table and round it to a divisible value by 5. For example, when the cell size is 116, the correct height should be 120. The point is that I use the adaptive layout to calculate the cell height. One of the subviews of UITableViewCell is a vertical dashed line which should connect to cell below. The dashed line consists of repeating of 5 points - dash (2 points) and gap (3 points). So the height of line view should be rounded up to the value divisible by 5 for correct connection with dashed line of cell wich is below. Two cells with connected dashed line Show your tried code? – Pratik Prajapati Jun 30 at 11:28 somebody has marked the question as duplicated without understanding the problem - never mind ... – ...

Get the uiSegmentControl value for edit

Get the uiSegmentControl value for edit i have a segment control to define the difficulty level for the preparation a recipe. I need to load the value assign at one recipe that I won't to edit it. The follow the code: @IBOutlet var segNewDifficultyLevel: UISegmentedControl! @IBOutlet var ingredientTableView: UITableView! @IBOutlet var directionTableView: UITableView! weak var delegate: AddNewRecipeViewControllerDelegate? // MARK: - Variabili Globali var editRecipe: RecipeModel! var difficultyLevel: String! var ingredients: [IngredientModel] = var directions: [DirectionModel] = This code is in the viewDidLoad: if let editToRecipe = editRecipe { title = "Edit Recipe" // Load data from Recipe Detail into editRecipe viewImageNewRecipe.image = editToRecipe.imageRecipe fieldNewRecipeName.text = editToRecipe.nameRecipe fieldNewQuantityFor.text = editToRecipe.quantityRecipe fieldNewPrepareTime.text = editToRe...

Storing app data under one entity Core Data

Storing app data under one entity Core Data I am making an app where a string is shown, and then they have to pick the correct string from 4 options. I need to update a score, based on whether they get it right or wrong. Let's call the string that is shown to them: shownString For ease and efficiency, I am planning to have ONE core data entity and only store one object for that entity, which will be a transformable type, that is an array with nested arrays/tuples, that contains shownString and the score for every shown string that could come up in multiple choice. The reason I am doing it like this as opposed to storing individual objects for each word and score is because it will make it easier to update the object i.e. delete and add it back in again. I am fairly new to Core Data, so please could you tell me if there are any problems with this, or if you think it is a good/acceptable way that will work well then please also tell me. Thanks What's t...

displaying a filtered video File with a preferredTransform that is not identity swift

displaying a filtered video File with a preferredTransform that is not identity swift For the app i'm working on, I need to provide a functionality that lets users apply filters to their videos( not real time, applying filters on a saved video and filePath is provided). addFilterToVideo is called when the user taps on a filter, a video composition is passed as a parameter to the initPlayer function and if the "none" video filter is tapped nil is passed whenever a new filter is tapped on I just change the video composition of the playerItem and the file is loaded only the first time func addFilterToVideo(filterName: String ){ if filterName != "" { let filter = CIFilter(name: filterName) if #available(iOS 9.0, *) { let composition = AVVideoComposition(asset: (self.playerItem?.asset)!) { (request) in let source = request.sourceImage.clampingToExtent() filter?.setValue(source, forKey: kCIInputImageKey) let outp...

swift: working with string

swift: working with string We have a simple string: let str = ""abc", "def","ghi" , 123.4, 567, "qwe,rty"" If we do this: let parsedCSV = str .components(separatedBy: .newlines) .filter { !$0.isEmpty } .map { $0.components(separatedBy: ",") } .map { $0.map { $0.trimmingCharacters(in: .whitespaces) } } print(parsedCSV) we get this: [[""abc"", ""def"", ""ghi"", "123.4", "567", ""qwe", "rty""]] Is there a simple solution (using functional programming) not to split the last element "qwe,rty" , because we know that it's one whole thing? "qwe,rty" That's not so simple. You need context to handle the " and in general it's easier to just go loop by the columns one by one. – Sulthan ...

Content Scroll to Row at Index Path beyond bonds?

Content Scroll to Row at Index Path beyond bonds? So I was able to have the annotation's callout animate when the selected table cell was selected like so. Quite simple due to the indexPath. func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let indexPath = indexPath.row myMap.selectAnnotation(pinArray[indexPath] , animated: true) } However, I do not understand how to achieve this when I select the annotation and want the table cell to light up. I've been attempting to set a var to indexPath but because the annotation has no subscript, I am unable to perform this. Therefore, how would I be able to accomplish the annotation to selected cell logic? func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) { //Magic } Update - currently the code I have to highlight the table cell correlated to the map annotation is this. func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) { let index = pinArray.index(of: ...

iOS Back Button Vertical Position

iOS Back Button Vertical Position I have a custom back button in my app in the Navigation Bar and for the life of me, cannot figure out why it is being pushed up. It is in normal position in iOS 11.0 and up, but for any version below 11.0, the image is pushed slightly up vertically (with the top of the button touching the bottom of the status bar). App Delegate Code: func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { let navigationBarAppearace = UINavigationBar.appearance() UINavigationBar.appearance().backIndicatorImage = UIImage(named: "backButton") UINavigationBar.appearance().backIndicatorTransitionMaskImage = UIImage(named: "backButton") UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffset(horizontal: 5.0, vertical: -60.0), for: .default) Has anyone else encountered this? Edit: Added two screenshots. First one shows on simulator in iOs 9.3 ...

Writing 0-Alpha in Metal shader doesn't render correctly

Writing 0-Alpha in Metal shader doesn't render correctly I'm trying to Chroma-Key an mp4 video playing over a UIView. I'm getting a texture every frame like so: var fullTex:CVMetalTexture? let w = CVPixelBufferGetWidthOfPlane(pixelBuffer, 0); let h = CVPixelBufferGetHeightOfPlane(pixelBuffer, 0); CVMetalTextureCacheCreateTextureFromImage(kCFAllocatorDefault, videoTextureCache!, pixelBuffer, nil, MTLPixelFormat.bgra8Unorm, w, h, 0, &fullTex) let fullTexture:MTLTexture? = CVMetalTextureGetTexture(fullTex!) Passing it to my shader like this: let commandBuffer = commandQueue.makeCommandBuffer()! let commandEncoder = commandBuffer.makeComputeCommandEncoder()! commandEncoder.setCom...