I am trying to have an image show up for 1 second and disappear after the 1 second is up. When I build my app it works fine but when I run my app it crashes. Here is my code:
var flashTimer = NSTimer()
var timerCounter = 0
var currentTime = 0
var randomImageGeneratorNumber = 0
var flashingImageView = UIImageView()
var flashButton = UIButton()
#IBAction func flashButton(sender: UIButton) {
var randomImageGeneratorNumber = arc4random_uniform(6) + 1
if flashButton.hidden {
flashButton.hidden = true
flashingImageView.hidden = false
}
if randomImageGeneratorNumber == 1 {
flashingImageView.image = UIImage(named: "Image1.png")
}
if randomImageGeneratorNumber == 2 {
flashingImageView.image = UIImage(named: "Image2.png")
}
if randomImageGeneratorNumber == 3 {
flashingImageView.image = UIImage(named: "Image3.png")
}
if randomImageGeneratorNumber == 4 {
flashingImageView.image = UIImage(named: "Image4.png")
}
if randomImageGeneratorNumber == 5 {
flashingImageView.image = UIImage(named: "Image5.png")
}
if randomImageGeneratorNumber == 6 {
flashingImageView.image = UIImage(named: "Image6.png")
}
var currentTime = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "timerFunc", userInfo: nil, repeats: false)
func timerFunc(sender: AnyObject){
flashingImageView.hidden = true;
}
}
The error in the debugger output is:
[Flash_Facts.ViewController timerFunc]: unrecognized selector sent to instance 0x7f9ceb774810
I am not sure how to fix this. Any suggestions?
Thanks in advance.
The problem is that you have to create your function outside the IBAction function. The same applies to your timer var ( currentTime )
var currentTime = NSTimer()
func timerFunc() {
flashButton.hidden = !flashButton.hidden
flashingImageView.hidden = !flashingImageView.hidden
}
#IBAction func flashButton(sender: UIButton) {
flashButton.hidden = !flashButton.hidden
flashingImageView.hidden = !flashingImageView.hidden
flashingImageView.image = UIImage(named: "Image\(arc4random_uniform(6) + 1).png")
currentTime = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "timerFunc", userInfo: nil, repeats: false)
}
Related
I am creating a memory game. In the first sequence all cards flip over and two cards matching cards will highlight. All cards will flip back over and randomly chosen cards will swap positions. I can get the values to swap using the array.swap array.shuffle functions, however I would like to animate the cards themselves swapping. I can get the cards to flip, however switching is another story. I have several other classes that go with this, but stackoverflow won't let me post more. If you need more detail please let me know.
My code:
struct findTheCardsFourCards: View {
#Namespace var cardAnimation: Namespace.ID
#State var flipped = false
#State var animate3d = false
#State var rememberTheCard = false
#State var timeRemaining = 15
#State var selectYourCardsText = false
#State var shuffleCards = false
let showCardsFirst = 15
let startGame = 11
let selectYourCards = 5
let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
#EnvironmentObject var game: CardModel
var rowCount = 2
var colCount = 2
var body: some View {
ZStack{
VStack{
ForEach(0 ..< game.cardInGame.count/rowCount){row in
HStack{
ForEach(0 ..< colCount){col in
CardView(card: game.cardInGame[row * rowCount + col], cardAnimation: cardAnimation, flipped: flipped, animate3d: animate3d, action: {game.cardInGame.swapAt(2, 3)})
.shadow(color: Color.purple, radius: highlightCards(card: game.cardInGame[row*rowCount+col]))
.animation(.linear)
.onReceive(timer, perform: { _ in
switch timeRemaining{
case 14:
flipped.toggle()
case 8:
game.cardInGame.swapAt(1,2)
default: break
}
/*
if timeRemaining > startGame {
game.cardInGame[row * rowCount + col].cardSelected = true
}
else if timeRemaining == startGame - 1{
game.cardInGame[row * rowCount + col].cardSelected = false
}
if timeRemaining == startGame {
shuffleCards = true
game.cardInGame.shuffle()
}*/
})
}
}
}
}
HStack{
Text("REMEMBER THE CARDS")
}
.opacity(rememberTheCard ? 1.0:0.0)
HStack{
Text("SELECT YOUR CARDS")
}
.opacity(selectYourCardsText ? 1.0 : 0.0)
//.layoutPriority(rememberTheCard ? 1.0:0.0)
}
.onReceive(timer, perform: { _ in
switch timeRemaining{
case 13:
rememberTheCard = true
game.flipGame.toggle()
case 10:
rememberTheCard = false
game.flipGame.toggle()
case 8:
game.cardInGame.swapAt(1, 3)
case 6:
selectYourCardsText = true
case 3:
selectYourCardsText = false
default:
break
}
/*if timeRemaining == showCardsFirst {
rememberTheCard = true
game.flipGame.toggle()
}
if timeRemaining == startGame {
rememberTheCard = false
game.flipGame.toggle()
}
if timeRemaining == startGame - 2 {
selectYourCardsText = true
}
if timeRemaining == selectYourCards{
selectYourCardsText = false
}*/
timeRemaining -= 1
})
}
func highlightCards(card: CardItem) -> CGFloat {
//if game.cardInGame[row*rowCount+col].winningCard == true{
if card.winningCard == true {
if game.flipGame == true{
return 10}}
if card.cardSelected == true{
return 10}
return 0
}
}
struct findTheCardsFourCards_Previews: PreviewProvider {
static var previews: some View {
findTheCardsFourCards()
.environmentObject(testCardModel)
.previewDevice("iPad Pro (9.7-inch)")
}
}
struct ContentView: View {
#EnvironmentObject var game: CardModel
#State private var timeRemaining = 5
let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
var body: some View {
VStack{
findTheCardsFourCards()
HStack{
Button(action: {game.flipGame.toggle()
} ) {
Text("Start Game")
}
}
.padding()
.padding()
.background(Color.green)
.cornerRadius(15)
.padding()
//.onReceive(timer){ time in
//if self.timeRemaining == 0 {
// self.timeRemaining -= 1
//}
//else{
// game.flipGame.toggle()
// }
//}
}
}
}
I want to capture a video through back camera using swiftUI. I can not find the proper solution on on video recording. I implement the code that record video automatically when view is open But I want to start the recording on bottom button click. Can someone please guide me on this.
import SwiftUI
import AVKit
struct RecordingView: View {
#State private var timer = 5
#State private var onComplete = false
#State private var recording = false
var body: some View {
ZStack {
VideoRecordingView(timeLeft: $timer, onComplete: $onComplete, recording: $recording)
VStack {
Button(action: {self.recording.toggle()}, label: {
ZStack {
Circle()
.fill(Color.white)
.frame(width: 65, height: 65)
Circle()
.stroke(Color.white,lineWidth: 2)
.frame(width: 75, height: 75)
}
})
Button(action: {
self.timer -= 1
print(self.timer)
}, label: {
Text("Toggle timer")
})
.foregroundColor(.white)
.padding()
Button(action: {
self.onComplete.toggle()
}, label: {
Text("Toggle completion")
})
.foregroundColor(.white)
.padding()
}
}
}
}
This is For recordingView
struct VideoRecordingView: UIViewRepresentable {
#Binding var timeLeft: Int
#Binding var onComplete: Bool
#Binding var recording: Bool
func makeUIView(context: UIViewRepresentableContext<VideoRecordingView>) -> PreviewView {
let recordingView = PreviewView()
recordingView.onComplete = {
self.onComplete = true
}
recordingView.onRecord = { timeLeft, totalShakes in
self.timeLeft = timeLeft
self.recording = true
}
recordingView.onReset = {
self.recording = false
self.timeLeft = 30
}
return recordingView
}
func updateUIView(_ uiViewController: PreviewView, context: UIViewRepresentableContext<VideoRecordingView>) {
}
}
extension PreviewView: AVCaptureFileOutputRecordingDelegate{
func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?) {
print(outputFileURL.absoluteString)
}
}
class PreviewView: UIView {
private var captureSession: AVCaptureSession?
private var shakeCountDown: Timer?
let videoFileOutput = AVCaptureMovieFileOutput()
var recordingDelegate:AVCaptureFileOutputRecordingDelegate!
var recorded = 0
var secondsToReachGoal = 30
var onRecord: ((Int, Int)->())?
var onReset: (() -> ())?
var onComplete: (() -> ())?
init() {
super.init(frame: .zero)
var allowedAccess = false
let blocker = DispatchGroup()
blocker.enter()
AVCaptureDevice.requestAccess(for: .video) { flag in
allowedAccess = flag
blocker.leave()
}
blocker.wait()
if !allowedAccess {
print("!!! NO ACCESS TO CAMERA")
return
}
// setup session
let session = AVCaptureSession()
session.beginConfiguration()
let videoDevice = AVCaptureDevice.default(.builtInWideAngleCamera,
for: .video, position: .front)
guard videoDevice != nil, let videoDeviceInput = try? AVCaptureDeviceInput(device: videoDevice!), session.canAddInput(videoDeviceInput) else {
print("!!! NO CAMERA DETECTED")
return
}
session.addInput(videoDeviceInput)
session.commitConfiguration()
self.captureSession = session
}
override class var layerClass: AnyClass {
AVCaptureVideoPreviewLayer.self
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var videoPreviewLayer: AVCaptureVideoPreviewLayer {
return layer as! AVCaptureVideoPreviewLayer
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
recordingDelegate = self
startTimers()
if nil != self.superview {
self.videoPreviewLayer.session = self.captureSession
self.videoPreviewLayer.videoGravity = .resizeAspect
self.captureSession?.startRunning()
self.startRecording()
} else {
self.captureSession?.stopRunning()
}
}
private func onTimerFires(){
print("🟢 RECORDING \(videoFileOutput.isRecording)")
secondsToReachGoal -= 1
recorded += 1
onRecord?(secondsToReachGoal, recorded)
if(secondsToReachGoal == 0){
stopRecording()
shakeCountDown?.invalidate()
shakeCountDown = nil
onComplete?()
videoFileOutput.stopRecording()
}
}
func startTimers(){
if shakeCountDown == nil {
shakeCountDown = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] (timer) in
self?.onTimerFires()
}
}
}
func startRecording(){
captureSession?.addOutput(videoFileOutput)
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let filePath = documentsURL.appendingPathComponent("tempPZDC")
videoFileOutput.startRecording(to: filePath, recordingDelegate: recordingDelegate)
}
func stopRecording(){
videoFileOutput.stopRecording()
print("🔴 RECORDING \(videoFileOutput.isRecording)")
}
}
Modify your code by this
struct VideoRecordingView: UIViewRepresentable {
#Binding var timeLeft: Int
#Binding var onComplete: Bool
#Binding var recording: Bool
func makeUIView(context: UIViewRepresentableContext<VideoRecordingView>) -> PreviewView {
let recordingView = PreviewView()
recordingView.onComplete = {
self.onComplete = true
}
recordingView.onRecord = { timeLeft, totalShakes in
self.timeLeft = timeLeft
self.recording = true
}
recordingView.onReset = {
self.recording = false
self.timeLeft = 30
}
return recordingView
}
func updateUIView(_ uiViewController: PreviewView, context: UIViewRepresentableContext<VideoRecordingView>) {
if recording {
uiViewController.start()
}
}
}
extension PreviewView: AVCaptureFileOutputRecordingDelegate{
func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?) {
print(outputFileURL.absoluteString)
}
}
class PreviewView: UIView {
private var captureSession: AVCaptureSession?
private var shakeCountDown: Timer?
let videoFileOutput = AVCaptureMovieFileOutput()
var recordingDelegate:AVCaptureFileOutputRecordingDelegate!
var recorded = 0
var secondsToReachGoal = 30
var onRecord: ((Int, Int)->())?
var onReset: (() -> ())?
var onComplete: (() -> ())?
init() {
super.init(frame: .zero)
var allowedAccess = false
let blocker = DispatchGroup()
blocker.enter()
AVCaptureDevice.requestAccess(for: .video) { flag in
allowedAccess = flag
blocker.leave()
}
blocker.wait()
if !allowedAccess {
print("!!! NO ACCESS TO CAMERA")
return
}
// setup session
let session = AVCaptureSession()
session.beginConfiguration()
let videoDevice = AVCaptureDevice.default(.builtInWideAngleCamera,
for: .video, position: .front)
guard videoDevice != nil, let videoDeviceInput = try? AVCaptureDeviceInput(device: videoDevice!), session.canAddInput(videoDeviceInput) else {
print("!!! NO CAMERA DETECTED")
return
}
session.addInput(videoDeviceInput)
session.commitConfiguration()
self.captureSession = session
}
override class var layerClass: AnyClass {
AVCaptureVideoPreviewLayer.self
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var videoPreviewLayer: AVCaptureVideoPreviewLayer {
return layer as! AVCaptureVideoPreviewLayer
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
recordingDelegate = self
}
func start() {
startTimers()
if nil != self.superview {
self.videoPreviewLayer.session = self.captureSession
self.videoPreviewLayer.videoGravity = .resizeAspect
self.captureSession?.startRunning()
self.startRecording()
} else {
self.captureSession?.stopRunning()
}
}
private func onTimerFires(){
print("🟢 RECORDING \(videoFileOutput.isRecording)")
secondsToReachGoal -= 1
recorded += 1
onRecord?(secondsToReachGoal, recorded)
if(secondsToReachGoal == 0){
stopRecording()
shakeCountDown?.invalidate()
shakeCountDown = nil
onComplete?()
videoFileOutput.stopRecording()
}
}
func startTimers(){
if shakeCountDown == nil {
shakeCountDown = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] (timer) in
self?.onTimerFires()
}
}
}
func startRecording(){
captureSession?.addOutput(videoFileOutput)
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let filePath = documentsURL.appendingPathComponent("tempPZDC")
videoFileOutput.startRecording(to: filePath, recordingDelegate: recordingDelegate)
}
func stopRecording(){
videoFileOutput.stopRecording()
print("🔴 RECORDING \(videoFileOutput.isRecording)")
}
}
I'm having extreme difficulty having callouts added to my annotations. I've removed any attempt at adding the callout from the code below.
The annotations are added at the bottom of the updateVisiblePins function
import UIKit
import MapKit
import CoreLocation
import Foundation
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
#IBOutlet weak var mapView: MKMapView!
var locationManager = CLLocationManager()
var landmarkToPass: String!
var rowIndex: Int!
struct MyVars {
static var prevLoc = CLLocation()
static var region = MKCoordinateRegion()
static var landmarks = [Landmark]()
static var landmark: Landmark = Landmark(title: String(), locationName: String(), discipline: String(), coordinate: CLLocationCoordinate2D())
}
override func viewDidLoad() {
super.viewDidLoad()
self.locationManager = CLLocationManager()
self.locationManager.delegate = self
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
self.mapView.showsUserLocation = true
var landmarks: [Landmark] = [Landmark]()
loadInitialData()
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
var prevLoc = MyVars.prevLoc
let userLoction: CLLocation = locations[0]
let distance = calculateDisatnceBetweenTwoLocations(prevLoc, destination: userLoction)
if prevLoc != userLoction {
prevLoc = userLoction
MyVars.prevLoc = userLoction
if distance > 5 {
let latitude = userLoction.coordinate.latitude
let longitude = userLoction.coordinate.longitude
let latDelta: CLLocationDegrees = 0.05
let lonDelta: CLLocationDegrees = 0.05
let span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta)
let location: CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
MyVars.region = MKCoordinateRegionMake(location, span)
self.mapView.showsUserLocation = true
self.mapView.setRegion(MyVars.region, animated: true)
updateVisiblePins()
} else {
let latitude = userLoction.coordinate.latitude
let longitude = userLoction.coordinate.longitude
let span = mapView.region.span
let location: CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
MyVars.region = MKCoordinateRegionMake(location, span)
self.mapView.showsUserLocation = true
updateVisiblePins()
}
}
}
func calculateDisatnceBetweenTwoLocations(source:CLLocation,destination:CLLocation) -> Double{
var distanceMeters = source.distanceFromLocation(destination)
var distanceKM = distanceMeters / 1000
return distanceKM
}
func updateVisiblePins() {
for (index, landmark) in MyVars.landmarks.enumerate() {
let landmarkLat = landmark.coordinate.latitude
let landmarkLon = landmark.coordinate.longitude
let userLocation = locationManager.location
let landmarkLocation = CLLocation(latitude: landmarkLat, longitude: landmarkLon)
let distance = calculateDisatnceBetweenTwoLocations(userLocation!, destination: landmarkLocation)
if distance < 30 {
mapView.addAnnotation(landmark)
} else {
if rowIndex != nil {
if index == rowIndex{
self.mapView.addAnnotation(landmark)
} else {
mapView.removeAnnotation(landmark)
}
}
}
}
}
func loadInitialData() {
// 1
let fileName = NSBundle.mainBundle().pathForResource("PublicLandmark", ofType: "json")
var data: NSData = NSData()
do {
data = try NSData(contentsOfFile: fileName!, options: [])
} catch {
}
// 2
var jsonObject: AnyObject!
do {
jsonObject = try NSJSONSerialization.JSONObjectWithData(data,
options: [])
} catch {
}
// 3
if let jsonObject = jsonObject as? [String: AnyObject],
// 4
let jsonData = JSONValue.fromObject(jsonObject)?["data"]?.array {
for landmarkJSON in jsonData {
if let landmarkJSON = landmarkJSON.array,landmark = Landmark.fromJSON(landmarkJSON) {
MyVars.landmarks.append(landmark)
}
}
}
}
}
The mapView.delegat = self line needs to be added to viewDidLoad() function.
I want to integrate the payU Money sdk in my app using swift2.0
I am using this sdk: https://github.com/payu-intrepos/Documentations/wiki/8.1-NEW-iOS-Seamless-SDK-integration
Where to create the test account for testing.
import UIKit
var merchantKey="your live merchant key"
var salt="your live merchant salt"
var PayUBaseUrl="https://secure.payu.in"
class PaymentScreen: UIViewController,UIWebViewDelegate {
#IBOutlet weak var myWebView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
self.initPayment()
}
func initPayment() {
var i = arc4random()
let amount = "1"
let productInfo = "Order"
let firstName = "Sample name"
let email = "abc#gmail.com"
let phone = "9999119911"
let sUrl = "https://www.google.com"
let fUrl = "https://www.bing.com"
let service_provider = "payu_paisa"
let strHash:String = self.sha1(String.localizedStringWithFormat("%d%#", i, NSDate()))
let rangeOfHello = Range(start: strHash.startIndex,
end: strHash.startIndex.advancedBy(20))
let txnid1 = strHash.substringWithRange(rangeOfHello)
let hashValue = String.localizedStringWithFormat("%#|%#|%#|%#|%#|%#|||||||||||%#",merchantKey,txnid1,amount,productInfo,firstName,email,salt)
let hash=self.sha1(hashValue)
let postStr = "txnid="+txnid1+"&key="+merchantKey+"&amount="+amount+"&productinfo="+productInfo+"&firstname="+firstName+"&email="+email+"&phone="+phone+"&surl="+sUrl+"&furl="+fUrl+"&hash="+hash+"&service_provider="+service_provider
let url = NSURL(string: String.localizedStringWithFormat("%#/_payment", PayUBaseUrl))
print("check my url", url, postStr)
let request = NSMutableURLRequest(URL: url!)
do {
let postLength = String.localizedStringWithFormat("%lu",postStr.characters.count)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Current-Type")
request.setValue(postLength, forHTTPHeaderField: "Content-Length")
request.HTTPBody = postStr.dataUsingEncoding(NSUTF8StringEncoding)
myWebView.loadRequest(request)
} catch {
}
}
func webViewDidStartLoad(webView: UIWebView) {
}
func webViewDidFinishLoad(webView: UIWebView) {
let requestURL = self.myWebView.request?.URL
let requestString:String = (requestURL?.absoluteString)!
if requestString.containsString("https://www.google.com") {
print("success payment done")
}
else if requestString.containsString("https://www.bing.com") {
print("payment failure")
}
}
func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
print("double failure")
}
func sha1(toEncrypt:String) -> String {
let data = toEncrypt.dataUsingEncoding(NSUTF8StringEncoding)!
var digest = [UInt8](count:Int(CC_SHA512_DIGEST_LENGTH), repeatedValue: 0)
CC_SHA512(data.bytes, CC_LONG(data.length), &digest)
let hexBytes = digest.map { String(format: "%02x", $0) }
return hexBytes.joinWithSeparator("")
}
}
// Swift 4
import UIKit
import SystemConfiguration
import Foundation
class PayUMoneyViewController: UIViewController, UIWebViewDelegate, UIAlertViewDelegate {
#IBOutlet weak var webView: UIWebView!
var merchantKey = "YOUR_MARCHANT_KEY"
var salt = "YOUR_SALT_KEY"
var PayUBaseUrl = "https://secure.payu.in"
var SUCCESS_URL = "https://www.payumoney.com/payments/guestcheckout/#/success"
var FAILED_URL = "https://www.PayUmoney.com/mobileapp/PayUmoney/failure.php"
#IBOutlet weak var activityIndicator: UIActivityIndicatorView!
var request = NSMutableURLRequest()
override func viewDidLoad() {
super.viewDidLoad()
self.webView.delegate = self
self.payPayment()
self.navigationItem.hidesBackButton = true
let newBackButton = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.plain, target: self, action: #selector(PayUMoneyViewController.back(sender:)))
self.navigationItem.leftBarButtonItem = newBackButton
}
#objc func back(sender: UIBarButtonItem) {
let alert = UIAlertController(title: "Cancel !", message: "Do you really want to cancel the transaction ?", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.default, handler: cancelTransaction))
alert.addAction(UIAlertAction(title: "No", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
func cancelTransaction( action : UIAlertAction)
{
_ = navigationController?.popToRootViewController(animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func payPayment() {
var i = arc4random()
let amount = "1"
let productInfo = "Transport"
let firstName = USER_FIRST_NAME // Geet
let email = USER_EMAIL // geetbasakare#gmail.com
let phone = USER_MOBILE_NO // 1234567890
let sUrl = "https://www.google.com"
let fUrl = "https://www.bing.com"
let service_provider = "payu_paisa"
let strHash:String = self.sha1(toEncrypt: String.localizedStringWithFormat("%d%#", i, NSDate()));
let r1 = strHash.range(of: strHash)!
// String range to NSRange:
let n1 = NSRange(r1, in: strHash)
print((strHash as NSString).substring(with: n1)) //
// NSRange back to String range:
let r2 = Range(n1, in: strHash)!
print(strHash.substring(with: r2))
let rangeOfHello = Range(n1, in: strHash)!
let txnid1 = strHash.substring(with: rangeOfHello)
let hashValue = String.localizedStringWithFormat("%#|%#|%#|%#|%#|%#|||||||||||%#",merchantKey,txnid1,amount,productInfo,firstName,email,salt)
let hash = self.sha1(toEncrypt: hashValue)
let postStr = "txnid="+txnid1+"&key="+merchantKey+"&amount="+amount+"&productinfo="+productInfo+"&firstname="+firstName+"&email="+email+"&phone="+phone+"&surl="+sUrl+"&furl="+fUrl+"&hash="+hash+"&service_provider="+service_provider
let url = NSURL(string: String.localizedStringWithFormat("%#/_payment", PayUBaseUrl))
print("check my url", url as Any, postStr)
let request = NSMutableURLRequest(url: url! as URL)
do {
let postLength = String.localizedStringWithFormat("%lu",postStr.characters.count)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Current-Type")
request.setValue(postLength, forHTTPHeaderField: "Content-Length")
request.httpBody = postStr.data(using: String.Encoding.utf8)
webView.loadRequest(request as URLRequest)
} catch {
print(error)
}
}
func webViewDidFinishLoad(_ webView: UIWebView) {
let requestURL = self.webView.request?.url
let requestString:String = (requestURL?.absoluteString)!
if (requestString == SUCCESS_URL) {
print("success payment done")
}
else if (requestString == FAILED_URL) {
print("payment failure")
}
}
func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
print("double failure")
}
func sha1(toEncrypt: String) -> String {
var digest = [UInt8](repeating: 0, count: Int(CC_SHA512_DIGEST_LENGTH))
if let data = toEncrypt.data(using: String.Encoding.utf8) {
let value = data as NSData
CC_SHA512(value.bytes, CC_LONG(data.count), &digest)
}
var digestHex = ""
for index in 0..<Int(CC_SHA512_DIGEST_LENGTH) {
digestHex += String(format: "%02x", digest[index])
}
return digestHex
}
/*
func sha1(toEncrypt:String) -> String {
var data = toEncrypt.data(using: String.Encoding.utf8)!
var digest = [UInt8](repeating: 0, count:Int(CC_SHA512_DIGEST_LENGTH))
_ = data.withUnsafeBytes {messageBytes in
CC_SHA512(messageBytes, CC_LONG(data.count), &digest)
}
let hexBytes = digest.map { String(format: "%02x", $0) }
return hexBytes.joined(separator: "")
}
*/
}
You can create a test account as described in the following help documentation, and you need not perform KYC in this regard. Later, you can use the Key and Salt on the Payment Gateway page of the Dashboard.
https://devguide.payu.in/low-code-web-sdk/getting-started-low-code-web-sdk/register-for-a-test-merchant-account/
I am trying to play a song based on the instrument the user selects. Here is my code:
#IBAction func play(sender: AnyObject) {
if isPlaying == false {
player.play()
isPlaying = true
}
}
#IBAction func stop(sender: AnyObject) {
if isPlaying == true {
player.stop()
isPlaying = false
}
}
#IBAction func pause(sender: AnyObject) {
if isPlaying == true {
isPlaying = false
player.pause()
}
}
var player = AVAudioPlayer()
var audioPath = NSBundle.mainBundle().pathForResource("Iditarod Bass", ofType: "m4a")
var isPlaying = Bool()
#IBOutlet var instrumentSelect: UISegmentedControl!
#IBAction func didChangeInstrument(sender: AnyObject) {
if isPlaying == false {
if instrumentSelect.selectedSegmentIndex == 0 {
audioPath = NSBundle.mainBundle().pathForResource("Iditarod Bass", ofType: "m4a")
do {
try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath!))
} catch {
}
} else if instrumentSelect.selectedSegmentIndex == 1 {
audioPath = NSBundle.mainBundle().pathForResource("Iditarod Cello", ofType: "m4a")
do {
try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath!))
} catch {
}
} else if instrumentSelect.selectedSegmentIndex == 2 {
audioPath = NSBundle.mainBundle().pathForResource("Iditarod Viola", ofType: "m4a")
do {
try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath!))
} catch {
}
} else if instrumentSelect.selectedSegmentIndex == 3 {
audioPath = NSBundle.mainBundle().pathForResource("Iditarod Violin 1", ofType: "m4a")
do {
try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath!))
} catch {
}
} else if instrumentSelect.selectedSegmentIndex == 4 {
audioPath = NSBundle.mainBundle().pathForResource("Iditarod Violin 2", ofType: "m4a")
do {
try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath!))
} catch {
}
}
}
}
All of them work fine except for the instrumentSelect.selectedSegmentIndex == 1. I don't know why. I get an EXC_BAD_INSTRUCTION that says fatal error: unexpectedly found nil while unwrapping an Optional value. The file is working fine, and I have cleaned the project numerous times. I have typed everything correctly. Why is that one not working? I am very confused about this, and I appreciate your help.
The file was not being added to the app target. It was added to the project only. Thanks #matt for helping me.