jituPatidar1992 / jitu

0 stars 0 forks source link

new Doc #1

Closed jituPatidar1992 closed 4 years ago

jituPatidar1992 commented 4 years ago

(4) BitBucket Add Project

https://bitbucket.org/dashboard/overview jitendra.ctinfotech@gmail.com Patidar@123 (2) now create project new folder in desktop (3) open terminal cd your project path then enter (4) copy bitbucket clone url (5) paste in to terminal and then enter (6) now open new folder and you can see inside new repository folder appear (7) now paste your project into this folder (8) now open terminal cd (your project path) (9) git add . (10) git commit -m "4-July-19 Project Created" //give comment if needs (11) git push

(6) CTI ApiCalling Format

 func updateCategoryandSubCat(withCat_id :Int, sub_id : Int,success: @escaping (_ user : [String:Any]) -> Void,error: @escaping (_ err: String) -> Void) {

       let url = "https://api.quickkitty.com/api/v1/user/updatesp"

       let params : Parameters = [
           "_method" : "PUT",
           "service_category" : withCat_id,
           "service_id" : sub_id
           ] as [String : Any]

       print(params)
       let usr_tkn = UserDefaults.standard.value(forKey: "Access_Token")
       let _headers : HTTPHeaders = ["Accept":"application/json","Authorization":"Bearer \(usr_tkn!)"]

       request(url, method: .post, parameters: params, encoding: URLEncoding.httpBody,headers: _headers).responseJSON(completionHandler:
           {
               response in
               print(response.result)
               switch (response.result)
               {
               case .success:
                   print("Success")
                   let jsonResponse = response.result.value as! [String: Any]
                   print(jsonResponse)

                   if let json_err = jsonResponse["message"] as? String {
                       print(json_err)
                       print("Please Login")

                   }
                   else
                   {
                       guard let responseObject = jsonResponse as? [String: Any] else {
                           return
                       }

                       success(responseObject)
                   }
                   break
               case .failure(let error2):
                   print(error2)
                   error(error2.localizedDescription)
                   break
               }

               })
   }

 Calling function :-
  UserService.instance.updateCategoryandSubCat(success: { (responseArray) in

        print(responseArray)
        let resp_code = responseArray["code"] as! String

        }, error: { (error) in
                appDelegate.hideHUD(self.view)
                Util.showAlertWithCallback(appName, message: "Server Error", isWithCancel: false)
            })

For LoginModel API Calling static func login(email: String, password:String, completionHandler: @escaping (Bool, JSON?, String?, Error?) -> Void) {

    let device_token = UserDefaults.standard.value(forKey: "Device_token")

    print(device_token ?? "")

    var parameters:Parameters = [:]
    parameters.updateValue(email, forKey: "email")
    parameters.updateValue(password, forKey: "password")
    parameters.updateValue(device_token!, forKey: "device_token")
    parameters.updateValue("1", forKey: "user_type")
    parameters.updateValue("ios", forKey: "device_type")

    let baseURL = IOUHOUConstants.API.baseUrl + IOUHOUConstants.API.login

    let headers: HTTPHeaders = ["Authorization": IOUHOUConstants.API.authorizationHeader]

    Alamofire.upload(multipartFormData:{ (multipartFormData) in

        for (key, value) in parameters {
            multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
        }
    }, usingThreshold:UInt64.init(),
       to:baseURL,
       method:.post,
       headers:headers,
       encodingCompletion: {
        result in

        switch result
        {
        case .success(let upload,_,_):
            upload.responseJSON { response in
                do
                {
                    DispatchQueue.main.async
                        {
                            if let value = response.result.value
                            {
                                print(value)
                                let responseJson = JSON(value)
                                if responseJson["code"].string == "1"
                                {
                                    completionHandler(true, responseJson, responseJson["message"].string, nil)
                                }
                                else if responseJson ["code"].string == "0"
                                {
                                    completionHandler(false, responseJson, responseJson["message"].string, nil)
                                }
                            }
                    }
                }
            }

        case .failure(let error):
            print("Error in upload: \(error.localizedDescription)")
            completionHandler(false, nil, error.localizedDescription, error)
        }
    })
}

For call IOUHOUAPIService.login(email: email, password: password) { (success, response, message, error) in }

(35) Move to Particular Controller extension UINavigationController { func backToViewController(viewController: Swift.AnyClass) { for element in viewControllers as Array { if element.isKind(of: viewController) { self.popToViewController(element, animated: true) break } } } }

For call:- self.navigationController?.backToViewController(viewController: InsertSimController.self)

(36) Rotation Image var timerTest: Timer? = nil timerTest = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true)

@objc func updateCounter() { var counter = 10 if counter > 0 { print("(counter) seconds to the end of the world") counter = counter - 1 self.rotateImage.transform = self.rotateImage.transform.rotated(by: .pi/4) } else { print("Timer stop") timerTest?.invalidate() timerTest = nil self.rotateImage.transform = CGAffineTransform(rotationAngle: 0) self.rotateImage.image = imageLiteral(resourceName: "hourglass") } }

(37) LoaderView Step1:- class ImageLoader: UIView {

// MARK: - Variables

lazy var animationLayer: CAShapeLayer = {
    return CAShapeLayer()
}()

var isAnimating: Bool = true
var hidesWhenStopped: Bool = false

// MARK: - Init

init(color: UIColor) {
    let frame: CGRect = CGRect(x: 0.0, y: 0.0, width: 48, height: 48)
    super.init(frame: frame)
    let image = self.getRelatedImage(color: color)
    animationLayer.frame = frame
    let animationImage = image
    animationLayer.contents = animationImage.cgImage
    animationLayer.masksToBounds = true
    self.layer.addSublayer(animationLayer)
    addRotation(forLayer: animationLayer)
   }

func getRelatedImage(color: UIColor) -> UIImage {
    var image =  imageLiteral(resourceName: "spinnerLarge")

    return image
}

required init(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}
override func didMoveToWindow() {
     //simpleAnimate()
    resume(layer: animationLayer)
 }
// MARK: - Func

func addRotation(forLayer layer: CALayer) {
    let rotation: CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")

    rotation.duration = 1.0
    rotation.isRemovedOnCompletion = false
    rotation.repeatCount = HUGE
    rotation.fillMode = CAMediaTimingFillMode.forwards
    rotation.fromValue = NSNumber(value: 0.0)
    rotation.toValue = NSNumber(value: 3.14 * 2.0)

    layer.add(rotation, forKey: "rotate")
}
func resume(layer: CALayer) {
    let pausedTime: CFTimeInterval = layer.timeOffset

    layer.speed = 1.0
    layer.timeOffset = 0.0
    layer.beginTime = 0.0

    let timeSincePause = layer.convertTime(CACurrentMediaTime(), from: nil) - pausedTime
    layer.beginTime = timeSincePause

    isAnimating = true
}

} Step2:- call that code in where you want to load

   let lodrView = ImageLoader(color: UIColor.red)
   self.loaderView.addSubview(lodrView)
     self.setLoaderView()

func setLoaderView() { loaderBgView.isHidden = false var seconds = 0 var timer = Timer() timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { (_) in if seconds > 3 { self.loaderBgView.isHidden = true timer.invalidate() } else { seconds += 1 } } timer.fire() }

(36) Add Image on Local notification:-

Step1:-

extension UNNotificationAttachment { static func create(identifier: String, image: UIImage, options: [NSObject: AnyObject]?) -> UNNotificationAttachment? { let fileManager = FileManager.default let tmpSubFolderName = ProcessInfo.processInfo.globallyUniqueString let tmpSubFolderURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(tmpSubFolderName, isDirectory: true) do { try fileManager.createDirectory(at: tmpSubFolderURL, withIntermediateDirectories: true, attributes: nil) let imageFileIdentifier = identifier+".png" let fileURL = tmpSubFolderURL.appendingPathComponent(imageFileIdentifier) let imageData = UIImage.pngData(image) try imageData()?.write(to: fileURL) let imageAttachment = try UNNotificationAttachment.init(identifier: imageFileIdentifier, url: fileURL, options: options) return imageAttachment } catch { print("error " + error.localizedDescription) } return nil } }

Step2:-

func scheduleNotification(onRepeact: Bool) { let dic = DevicesShared.shared.getRandomDevice() let content = UNMutableNotificationContent() let categoryIdentifire = "Delete Notification Type" content.title = dic["deviceName"] as? String ?? "" content.body = kDeviceKickedOut content.sound = UNNotificationSound.default content.userInfo = dic content.categoryIdentifier = categoryIdentifire let myImage = UIImage(imageLiteralResourceName: "samsungSmallUnAuth") if let attachment = UNNotificationAttachment.create(identifier: "image", image: myImage, options: nil) { content.attachments = [attachment] } let thisTime: TimeInterval = 60.0 let trigger = UNTimeIntervalNotificationTrigger(timeInterval: thisTime, repeats: onRepeact) let identifier = "Local Notification" let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger) notificationCenter.add(request) { (error) in if let error = error { print("Error (error.localizedDescription)") } } let snoozeAction = UNNotificationAction(identifier: "Snooze", title: "Snooze", options: []) let deleteAction = UNNotificationAction(identifier: "DeleteAction", title: "Delete", options: [.destructive]) let category = UNNotificationCategory(identifier: categoryIdentifire, actions: [snoozeAction, deleteAction], intentIdentifiers: [], options: []) notificationCenter.setNotificationCategories([category]) }

(37) Image Tapped by Gesture Action :- func imageTapSetup() { let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.cellTappedMethod(:))) self.userImage.isUserInteractionEnabled = true self.userImage.addGestureRecognizer(tapGestureRecognizer) } @objc func cellTappedMethod( sender: AnyObject) { print("ImgTapped") }

(38) Get String with Data Formate

extension Date { func getStringFromDate() -> String { let formatter = DateFormatter() // initially set the format based on your datepicker date / server String formatter.dateFormat = "d MMM, h:mm a" // again convert your date to string let myStringafd = formatter.string(from: self) // print(myStringafd) return myStringafd } } Call:- self.lblTime.text = detailObj.date.getStringFromDate()

(39) TabelView Swipe Action method:-

func tableView( tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { if indexPath.section == 2 { let deviceObj = self.getDevicesFor(auth: TabTypes.authorizedDevice == selectedTabType)[indexPath.row] let title = !deviceObj.devicceIsPlay ? "Play" : "Pause" let imageName = !deviceObj.devicceIsPlay ? "playWhite.png" : "swipePause.png" let bgColor = !deviceObj.devicceIsPlay ? playColor : pauseColor let deleAction = UIContextualAction(style: .normal, title: "Unauthorize", handler: { (, , completionHandler ) in self.actionOnSwipeUnauthorize(indexPath: indexPath) completionHandler(true) }) deleAction.image = UIImage(named: "swipeDelete.png") deleAction.backgroundColor = UIColor(red: 1.0, green: 58.0 / 255.0, blue: 58.0 / 255.0, alpha: 1.0) let pauseAction = UIContextualAction(style: .normal, title: title, handler: { (, _, completionHandler ) in deviceObj.devicceIsPlay ? self.actionOnSwipePause(indexPath: indexPath) : self.actionOnSwipePlay(indexPath: indexPath) completionHandler(true) }) pauseAction.image = UIImage(named: imageName) pauseAction.backgroundColor = bgColor let configuration = UISwipeActionsConfiguration(actions: [deleAction, pauseAction]) return configuration } return nil }

(40) Save Model Data In Userdefaults:-

func saveUserDetail(userDetailObj: UserDetailModel) { do { let encodedData = try NSKeyedArchiver.archivedData(withRootObject: userDetailObj, requiringSecureCoding: false) let userDefaults = UserDefaults.standard userDefaults.set(encodedData, forKey: kUserDetail) userDefaults.synchronize() } catch { print(error.localizedDescription) } }

(41) Add Tuples in Function Parameter:- func addValuesOnAlertEntityDB(alertDB:(entity: String, deviceiD: Int, deviceName: String), message: String, mobileId: Int64, noficationType: AlertNotificationType, deviceType: String) {}

(42) Online Swift Playground:-

  http://online.swiftplayground.run/

(43) Dispatch Que with timer :-

DispatchQueue.main.asyncAfter(deadline: .now() + 0.9) { }

(44) ScrollView get current Index:-

var scrollsize = CGSize(width: 0, height: 0)

func setUpUi() {
    self.view.layoutIfNeeded()
    let height: CGFloat = self.view.frame.size.height
    let width: CGFloat = self.view.frame.size.width
    scrollsize = CGSize(width: width, height: height)
}

extension InsightsSurveyVC: UIScrollViewDelegate { func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer) { let pageWidth = scrollsize.width let itemIndex = (targetContentOffset.pointee.x) / pageWidth let index = IndexPath(item: Int(round(itemIndex)), section: 0) self.pageControl.currentPage = index.item } }

(45) Set Shadow on View :- func setShadow() { insightMainView.layer.shadowColor = UIColor.lightGray.cgColor insightMainView.layer.shadowOpacity = 1.0 insightMainView.layer.shadowOffset = CGSize(width: 0, height: 1) insightMainView.layer.shadowRadius = 4 insightMainView.layer.borderWidth = 0.0 insightMainView.layer.borderColor = UIColor.clear.cgColor insightMainView.clipsToBounds = false insightMainView.layer.cornerRadius = 15 insightMainView.backgroundColor = UIColor.white }

(46) Get Method API Calling through Alamofire

func CampListApi() { var request = URLRequest(url: URL(string:"http://telanganaschoolapp-env.us-west-2.elasticbeanstalk.com/govt/camp/list")!) print(request) request.httpMethod = "GET" request.setValue("application/json", forHTTPHeaderField: "Content-Type") Alamofire.request(request).responseString { response in switch response.result { case .success: if let json = response.result.value { print(json) let data = json.data(using: .utf8)! if let parsedData = try? JSONSerialization.jsonObject(with: data) as! [String:Any] { let msgcode = parsedData["result"] as! Bool // print result type message according to api in condition of true or false print(msgcode) if msgcode == true{ print(msgcode) let array = parsedData["campList"] as? NSArray print(array as Any) } }} case.failure(let error): print(error) } }

}

(46) POST Method API Calling through Alamofire

func addCandidateApi(canName :String, canEmail : String,canNumber : String,success: @escaping ( user : [String:Any]) -> Void,error: @escaping ( err: String) -> Void) { let _headers : HTTPHeaders = ["Content-Type":"application/x-www-form-urlencoded"] let params : Parameters = [ "name" : canName, "email" : canEmail, "contact_number" : canNumber ] as [String : Any] request(baseUrl, method: .post, parameters: params, encoding: URLEncoding.httpBody , headers: _headers).responseJSON(completionHandler: { response in response let jsonResponse = response.result.value as! NSDictionary success(jsonResponse as! [String : Any]) }) }

(47) JSON converter in Swift class Model https://www.json4swift.com/

(48) Check Internet Availability Setup :- Step 1:- create class .swift class name internet.swift

// // Internet.swift // CandidateAppDemo // // Created by mac on 27/09/20. // Copyright © 2020 mac. All rights reserved. //

import Foundation import SystemConfiguration import UIKit import SystemConfiguration.CaptiveNetwork public let ReachabilityStatusChangedNotification = "ReachabilityStatusChangedNotification"

public enum ReachabilityType: CustomStringConvertible { case WWAN case WiFi

public var description: String {
    switch self {
    case .WWAN: return "WWAN"
    case .WiFi: return "WiFi"
    }
}

}

public enum ReachabilityStatus: CustomStringConvertible { case Offline case Online(ReachabilityType) case Unknown

public var description: String {
    switch self {
    case .Offline: return "Offline"
    case .Online(let type): return "Online (\(type))"
    case .Unknown: return "Unknown"
    }
}

} public class Reachability {

func connectionStatus() -> ReachabilityStatus {
    var zeroAddress = sockaddr_in()
    zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
    zeroAddress.sin_family = sa_family_t(AF_INET)

    guard let defaultRouteReachability = (withUnsafePointer(to: &zeroAddress) {
        $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { zeroSockAddress in
            SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
        }
    }) else {
       return .Unknown
    }

    var flags : SCNetworkReachabilityFlags = []
    if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
        return .Unknown
    }

    return ReachabilityStatus(reachabilityFlags: flags)
}

func monitorReachabilityChanges() {
    let host = "google.com"
    var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
    let reachability = SCNetworkReachabilityCreateWithName(nil, host)!

    SCNetworkReachabilitySetCallback(reachability, { (_, flags, _) in
        let status = ReachabilityStatus(reachabilityFlags: flags)

        NotificationCenter.default.post(name: NSNotification.Name(rawValue: ReachabilityStatusChangedNotification), object: nil, userInfo: ["Status": status.description])}, &context)

    SCNetworkReachabilityScheduleWithRunLoop(reachability, CFRunLoopGetMain(), CFRunLoopMode.commonModes.rawValue)
}

}

extension ReachabilityStatus {

public init(reachabilityFlags flags: SCNetworkReachabilityFlags) {
    let connectionRequired = flags.contains(.connectionRequired)
    let isReachable = flags.contains(.reachable)
    let isWWAN = flags.contains(.isWWAN)

    if !connectionRequired && isReachable {
        if isWWAN {
            self = .Online(.WWAN)
        } else {
            self = .Online(.WiFi)
        }
    } else {
        self =  .Offline
    }
}

}

Step 2: - call in viewDidLoad() Reachability().monitorReachabilityChanges() NotificationCenter.default.addObserver(self, selector: #selector(self.reachabilityChanged), name: NSNotification.Name("ReachabilityStatusChangedNotification"), object: nil)

@objc func reachabilityChanged(notification: Notification) { print("Yes got it") }

jituPatidar1992 commented 4 years ago

sdsdfs