iOS 16.2 expands AirDrop 10-minute limit for all users

In iOS 16.2 Everyone for airdrop can still be enabled to allow users to receive content from anyone, but it  will turn off after a 10 minuteand  change to Contacts Only. The tweak will require users to explicitly activate AirDrop to receive files and photos from unknown.

According to an online user report Apple says it is improving the AirDrop experience by automatically reverting the  to Contacts Only after 10 minutes to help ease unwanted file sharing.

Apple drew criticism for this change, as protesters in China had been using AirDrop to spread posters and other content in opposition to the prime minister or the Chinese government. The Chinese government is believed to have made the change request to Apple, and Apple respect that request.

The default setting of AirDrop is Contacts Only. A user needs to manually change the setting to receive files from Everyone.

How to play audio from url

    func saveFile(url:URL){

        let docUrl:URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! as URL

    let desURL = docUrl.appendingPathComponent(“sample.mp3”) //Use file name with ext

    var downloadTask:URLSessionDownloadTask

    downloadTask = URLSession.shared.downloadTask(with: url, completionHandler: { [weak self](URLData, response, error) -> Void in

        do{

            let isFileFound:Bool? = FileManager.default.fileExists(atPath: desURL.path)

            if isFileFound == true{

                print(desURL)

                self?.playSound(path: desURL.path)

            } else {

                try FileManager.default.copyItem(at: URLData!, to: desURL)

                self?.playSound(path: desURL.path)

            }

        }catch let err {

            print(err.localizedDescription)

        }

    })

    downloadTask.resume()

    }

    func playSound(path : String) {

        let url = URL(fileURLWithPath: path)

        do {

            //let data = try Data(contentsOf: url)

            player = try AVAudioPlayer(contentsOf: url)

            player?.play()

        } catch let error {

            print(error.localizedDescription)

        }

    }

USE HERE

 self.saveFile(url: yoururl)

How to map an array in a Firestore document to Swift?

struct maindata {

    var userID: String

    var extended: [Contents]

    init(Doc: DocumentSnapshot) {

        self.userID = Doc.get(“userID”) as? String ?? “nil”

        extended = []

        let data = Doc.data( )

        if let testarr = data?[“testarr”] as? [[String: Any]]{

            testarr.forEach { sany in

                if let content = Contents(data: sany){

                    self.extended.append(content)

                }

            }

        }

    }

}

struct Contents {

    var IDone: String

    var IDtwo: String

    init?(data: [String: Any]) {

        self.IDone = data[“one”] as? String ?? “”

        self.IDtwo = data[“two”] as? String ?? “”

    }

}

How to use example

Firestore.firestore().collection(“LiveApi”).document(“test”).getDocument { docsnap, error in

            if let docs = docsnap {

                let data = maindata(Doc: docs)

                data.extended.first?.IDone

                data.extended[1].IDtwo

            }

        }

How to get steps from Fitbit in swift

How to get steps from Fitbit

First of all setup Fitbit account in https://dev.fitbit.com/

Get Client id & Client Secret from Fitbit dashboard

set Identifier and URL Scheme

-> identifier = your bundle id

-> URL Schemes : your web url

Create model for Fitbit credential

class FitbitAPI {
	
	static let sharedInstance: FitbitAPI = FitbitAPI()
	
	static let baseAPIURL = URL(string:"https://api.fitbit.com/1")
	
	func authorize(with token: String) {
		let sessionConfiguration = URLSessionConfiguration.default
		var headers = sessionConfiguration.httpAdditionalHeaders ?? [:]
		headers["Authorization"] = "Bearer \(token)"
		sessionConfiguration.httpAdditionalHeaders = headers
		session = URLSession(configuration: sessionConfiguration)
	}
	
	var session: URLSession?
}

class ViewController: UIViewController,AuthenticationProtocol {
    
    var authenticationController: AuthenticationController?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        authenticationController = AuthenticationController(delegate: self)
    }
    
    
    private func retrivedataFromFitbit() {
        
        if let authToken = UserDefaults.standard.string(forKey: "authToken") {
              FitbitAPI.sharedInstance.authorize(with: authToken)
          
              fetchFitbitActivity.fetchFitbitActivity(date: Date()) { (steps) in
              print(steps ?? 0)
            }
        }
    }
}

Fetch Fitbit activity model

import Foundation


import SafariServices
import AuthenticationServices

typealias AuthHandlerCompletion = (URL?, Error?) -> Void

class AuthContextProvider: NSObject {

    private weak var anchor: ASPresentationAnchor!

    init(_ anchor: ASPresentationAnchor) {
        self.anchor = anchor
    }

}

extension AuthContextProvider: ASWebAuthenticationPresentationContextProviding {

    @available(iOS 12.0, *)
    func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
        return anchor
    }

}

protocol AuthHandlerType: class {
    var session: NSObject? { get set }
    var contextProvider: AuthContextProvider? { get set }
    func auth(url: URL, callbackScheme: String, completion: @escaping AuthHandlerCompletion)
}

extension AuthHandlerType {

    func auth(url: URL, callbackScheme: String, completion: @escaping AuthHandlerCompletion) {
        if #available(iOS 12, *) {
            let session = ASWebAuthenticationSession(url: url, callbackURLScheme: callbackScheme) {
                url, error in
                completion(url, error)
            }
            if #available(iOS 13.0, *) {
                session.presentationContextProvider = contextProvider
            } else {
                // Fallback on earlier versions
            }
            session.start()
            self.session = session
        } else {
            let session = SFAuthenticationSession(url: url, callbackURLScheme: callbackScheme) {
                url, error in
                completion(url, error)
            }
            session.start()
            self.session = session
        }
    }

}

struct Constants {

    static let authUrl = URL(string: "https://www.fitbit.com/oauth2/authorize")
    static let responseType = "code"
    static let clientId = "your client id"
    static let redirectScheme = "your web url://m"
    static let redirectUrl = "\(redirectScheme)fitbit/auth"
    static let scope = ["activity", "heartrate", "location", "nutrition", "profile", "settings", "sleep", "social", "weight"]
    static let expires = "604800"

    private init() {}

}

class Model: AuthHandlerType {

    var session: NSObject? = nil
    var contextProvider: AuthContextProvider?

    func auth(_ completion: @escaping ((String?, Error?) -> Void)) {
        guard let authUrl = Constants.authUrl else {
            completion(nil, nil)

            return
        }

        var urlComponents = URLComponents(url: authUrl, resolvingAgainstBaseURL: false)
        urlComponents?.queryItems = [
            URLQueryItem(name: "response_type", value: Constants.responseType),
            URLQueryItem(name: "client_id", value: Constants.clientId),
            URLQueryItem(name: "redirect_url", value: Constants.redirectUrl),
            URLQueryItem(name: "scope", value: Constants.scope.joined(separator: " ")),
            URLQueryItem(name: "expires_in", value: String(Constants.expires))
        ]

        guard let url = urlComponents?.url else {
            completion(nil, nil)

            return
        }

        auth(url: url, callbackScheme: Constants.redirectScheme) {
            url, error in
            if error != nil {
                completion(nil, error)
            } else if let `url` = url {
                guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false),
                      let item = components.queryItems?.first(where: { $0.name == "code" }),
                      let code = item.value else {
                    completion(nil, nil)

                    return
                }
                completion(code, nil)
            }
        }
    }

}


class fetchFitbitActivity {
    
    static func fetchFitbitActivity(date : Date , callback: @escaping (Int)->()){
    
    //static func fetchFitbitActivity(arg: Bool, completion: (Bool) -> ()) {
        
        let dateformatter = DateFormatter()
        dateformatter.dateFormat = "yyyy-MM-dd"
        dateformatter.timeZone = TimeZone(identifier: "UTC")
        dateformatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale?
        var datePath = dateformatter.string(from: date)
        datePath = datePath + ".json"
        
        print(datePath)
        guard let session = FitbitAPI.sharedInstance.session,
            let stepURL = URL(string: "https://api.fitbit.com/1/user/-/activities/date/\(datePath)") else {
                
                callback(0)
        
                return
        }
         

        
        let dataTask = session.dataTask(with: stepURL) { (data, response, error) in
            guard let response = response as? HTTPURLResponse, response.statusCode < 300 else {

                callback(0)
                return
            }
            do {
                let jsonDecoder = JSONDecoder()
                guard let data = data,
                    let dictionary = (try jsonDecoder.decode(Json4Swift_Base_Fitbit_Exercise.self, from: data)) as? Json4Swift_Base_Fitbit_Exercise else {

                        callback(0)
                        return
                }
                //let Activities = dictionary.activities ?? []
                let TotalStepCount = dictionary.summary?.steps ?? 0
                print(TotalStepCount)
                callback(TotalStepCount)
                
            }catch{
                print(error.localizedDescription)
            }

        }
        dataTask.resume()
    }
}

Fitbit data Model

import Foundation
struct Json4Swift_Base_Fitbit_Exercise : Codable {
	let activities : [Activities]?
	let goals : Goals?
	let summary : Summary?

	enum CodingKeys: String, CodingKey {

		case activities = "activities"
		case goals = "goals"
		case summary = "summary"
	}

	init(from decoder: Decoder) throws {
		let values = try decoder.container(keyedBy: CodingKeys.self)
		activities = try values.decodeIfPresent([Activities].self, forKey: .activities)
		goals = try values.decodeIfPresent(Goals.self, forKey: .goals)
		summary = try values.decodeIfPresent(Summary.self, forKey: .summary)
	}

}

How get Steps from Apple health kit in swift

First of all add HealthKit on Capability in project singing & Capability

    static func retrieveStepCount(today:Date, yesterDay: Date,completion: @escaping(Double?,Error?) -> ()) {
        
           let inputFormatter = DateFormatter()
           inputFormatter.dateFormat = "dd/MM/yyyy"
           
           //   Define the Step Quantity Type
           let stepsCount = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)
           
           //  Set the Predicates & Interval
           let predicate = HKQuery.predicateForSamples(withStart: today.startOfDay , end: today.endOfDay, options: .strictStartDate)
           var interval = DateComponents()
           interval.day = 1
           //print(predicate)
           
           let query = HKStatisticsQuery(quantityType: stepsCount!, quantitySamplePredicate: predicate, options: HKStatisticsOptions.cumulativeSum) { (query, result, error) in

               var resultCount = 0.0
               if error != nil {
                   completion(nil, error)
                   return
               }
               
               if let myResult = result {
                   if let sum = myResult.sumQuantity() {
                       print(sum)
                       resultCount = sum.doubleValue(for: HKUnit.count())
                   }
                   
                   DispatchQueue.main.async {
                       completion(resultCount, nil)
                   }
               }
           }
           HKHealthStore().execute(query)
       }

Call above function and get steps

 let startDate = Date().startOfDay
 let yesterDay = Date().endOfDay

self.retrieveStepCount(today: startDate, yesterDay: yesterDay) { (steps, error) in
            print(error?.localizedDescription)
            
            if error == nil {
                
                print("Health kit Walked steps  \(steps ?? 0)")
            }
}

How check internet connection on one place to whole app in swift

Note : not require to check internet connection in all view controller just add code on launch app.

        import Network
        
        let monitor = NWPathMonitor()
        
        let queue = DispatchQueue(label: "NetStatus_Monitor")
        monitor.start(queue: queue)
        
        monitor.pathUpdateHandler = { path in
            if path.status == .satisfied {
                
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
                self.InternetConnectionAlert("Warnning", "We are connected to internet")
           }
                
            } else {
             
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {  
                self.InternetConnectionAlert("Warnning", "We are not connected to internet")
            }
            }

            print(path.isExpensive)
        }
        
        private func InternetConnectionAlert(_ title : String, _ Body : String) {
            
            let alert = UIAlertController(title: title, message: Body, preferredStyle: .alert)
            
            alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
                  switch action.style{
                  case .default:
                    print("cancel")
                
                  case .cancel:
                        print("cancel")

                  case .destructive:
                        print("destructive")
            }}))
            
            UIApplication.shared.keyWindow?.rootViewController?.present(alert,animated: true,completion: nil)
            
        }

if you want to stop network monitoring

monitor.cancel()

Present alert on window in swift 5

how to present alert in window in swift

func showAlert(_ title: String, _ message: String) {
        let alert = UIAlertController(
            title: title, 
            message: message, 
            preferredStyle: UIAlertControllerStyle.alert
        )

        alert.addAction(UIAlertAction(
            title: "OK", 
            style: UIAlertActionStyle.default, 
            handler: nil
        ))

       alert.addAction(UIAlertAction(
            title: "Cancel", 
            style: UIAlertActionStyle.default, 
            handler: nil
        ))

        UIApplication.shared.keyWindow?.rootViewController?.present(
            alert, 
            animated: true, 
            completion: nil
        )
    }

Get tableview height using observer in swift

first of first set observer in viewdidLoad using blow code

tableView.addObserver(self, forKeyPath: "contentSize", options: .new, context: nil)

Then add observer value function for getting tableview height whenever content is updated

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if (object as! UITableView) == self.tableView {
      if(keyPath == "contentSize"){
        if let newvalue = change?[.newKey]
        {
          let newsize = newvalue as! CGSize
          print(newsize.height)
          //yourtableview.height = newsize.height 
        }
      }
    }
  }

In last remove observer from viewwillDisapper

if tableView.observationInfo != nil{
      tableView.removeObserver(self, forKeyPath: "contentSize")
    }

Developed by : Krina Kathiriya

set local notification and get pending notification and remove local notification in swift

how to set local notification in swift

        let content = UNMutableNotificationContent()
        content.title = "notification title"
        content.categoryIdentifier = "identifier"
        content.body = "notification body"
        content.sound = UNNotificationSound.default
        
        let triggerDateComponent = Calendar.current.dateComponents([.day, .hour, .minute], from: Date().addHours(5))
        
        let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDateComponent, repeats: false)
        
        let request = UNNotificationRequest(identifier: "notification identifier", content: content, trigger: trigger)
        
        UNUserNotificationCenter.current().add(request, withCompletionHandler: { (error) in
           if error != nil {
               print(error!)
               
           } else {
               print("\(request.description)")
           }
       })


how to get pending notification in swift

center.getPendingNotificationRequests { (notifications) in
            print("Count: \(notifications.count)")
                
            for item in notifications {
                
                let id = item.identifier
                let time = item.content
                let categoryId = time.categoryIdentifier
                print(time)
                print("id: \(id)")
                guard let trigger = item.trigger as? UNCalendarNotificationTrigger else { return }
                var day = trigger.dateComponents.weekday
                let nextFireDate = trigger.nextTriggerDate()
                let title = item.content.body
                }
   }

how to remove notification in swift

UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: ["notification identifire"])

Clickable attributed text in swift

for example if you set privacy policy text in single line with multiple click in swift

let attributedString = NSMutableAttributedString(string: "By continueing you agree terms and conditions and the privacy policy")

attributedString.addAttribute(.link, value: "<a href="https://pathanikbal.wordpress.com">https://yourlink</a>", range: (attributedString.string as NSString).range(of: "terms and conditions"))

attributedString.addAttribute(.link, value: "https://pixsterstudio.com/terms-of-use.html", range: (attributedString.string as NSString).range(of: "privacy policy"))

textview.backgroundColor = UIColor(named: "newBGColor")
textview.textAlignment = .center
textview.linkTextAttributes = [ NSAttributedString.Key.foregroundColor: UIColor.blue]
textview.attributedText = attributedString
textview.delegate = self
textview.isSelectable = true
textview.isEditable = false
textview.delaysContentTouches = false
textview.isScrollEnabled = false
textview.font = UIFont(name: "AvenirNext-Regular", size: 10)


func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {

            if URL.scheme == "terms" {
                print("---- TERMS & CONDITION -----")
                return false

            } else  if URL.scheme == "privacy"{
                print("---- PRIVACY & POLICY -----")
                 return false
            }
            return true
 }