Friday, December 21, 2018

Upload UIImage as base64 String

Upload UIImage as Base64 String

(Upload UIImage as string)

//Select Pic From Camera or Gallery 
    

@objc func btnProfileImageSelection(geture:UIGestureRecognizer) {
        //Create the AlertController and add Its action like button in Actionsheet
        let actionSheetControllerIOS8: UIAlertController = UIAlertController(title: "Choose photo...", message: "", preferredStyle: .actionSheet)
        
        let cancelActionButton = UIAlertAction(title: "Cancel", style: .cancel) { _ in
            print("Cancel")
        }
        actionSheetControllerIOS8.addAction(cancelActionButton)
        
        let saveActionButton = UIAlertAction(title: "Camera", style: .default)
        { _ in
            print("Camera")
            
            if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.camera){
                let imag = UIImagePickerController()
                imag.delegate = self
                imag.sourceType = UIImagePickerController.SourceType.camera;
                imag.allowsEditing = true
                self.present(imag, animated: true, completion: nil)
            }
            
        }
        actionSheetControllerIOS8.addAction(saveActionButton)
        
        let deleteActionButton = UIAlertAction(title: "Gallery", style: .default)
        { _ in
            print("Gallery")
            
            if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.photoLibrary){
                let imag = UIImagePickerController()
                imag.delegate = self
                imag.sourceType = UIImagePickerController.SourceType.photoLibrary;
                //imag.mediaTypes = [kUTTypeImage];
                imag.allowsEditing = true
                self.present(imag, animated: true, completion: nil)
                
            }
        }
        actionSheetControllerIOS8.addAction(deleteActionButton)
        self.present(actionSheetControllerIOS8, animated: true, completion: nil)
        
    }
    
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        
        // The info dictionary may contain multiple representations of the image. You want to use the original.
        guard let selectedImage = info[.originalImage] as? UIImage else {
            fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
        }
        
        // Set photoImageView to display the selected image.
        self.imgUser.image = selectedImage
//Compress image quality
        let imageData = selectedImage.jpegData(compressionQuality: 0.1)
        
//Here Image converted into base64 string

                let strBase64 = imageData?.base64EncodedString() ?? ""         picker.dismiss(animated: true, completion: nil)

    }

Thursday, July 5, 2018

Set UIView Shadow

Set UIView Shadow


//MARK: View Shadow
    func viewShadow(myView: UIView) -> UIView {
        myView.layer.shadowColor = UIColor.black.cgColor
        myView.layer.shadowOpacity = 1
        myView.layer.shadowOffset = CGSize.zero
        myView.layer.shadowRadius = 1
        myView.layer.shadowPath = UIBezierPath(rect: myView.bounds).cgPath
        myView.layer.shouldRasterize = true
        return myView
    }

Time calculation from given date

This will show no of seconds, minutes, hours, days, weeks, months and year passed or yet to pass from given date.



public func timeAgoSince(_ date: Date) -> String {
    
    let calendar = Calendar.current
    let now = Date()
    let unitFlags: NSCalendar.Unit = [.second, .minute, .hour, .day, .month, .year]
    let components = (calendar as NSCalendar).components(unitFlags, from: date, to: now, options: [])
    
    if let year = components.year, year >= 2 {
        return "\(year) years ago"
    }
    
    if let year = components.year, year >= 1 {
        return "Last year"
    }
    
    if let month = components.month, month >= 2 {
        return "\(month) months ago"
    }
    
    if let month = components.month, month >= 1 {
      return "\(month) month ago"
        // return "Last month"
    }
    
//    if let week = components.weekOfYear, week >= 2 {
//        return "\(week) weeks ago"
//    }
//    
//    if let week = components.weekOfYear, week >= 1 {
//        return "Last week"
//    }
    
    if let day = components.day, day >= 2 {
        return "\(day) days ago"
    }
    
    if let day = components.day, day >= 1 {
        return "\(day) day ago"
        //return "Yesterday"
    }
    
    if let hour = components.hour, hour >= 2 {
        return "\(hour) hours ago"
    }
    
    if let hour = components.hour, hour >= 1 {
        return "An hour ago"
    }
    
    if let minute = components.minute, minute >= 2 {
        return "\(minute) minutes ago"
    }
    
    if let minute = components.minute, minute >= 1 {
        return "A minute ago"
    }
    
    if let second = components.second, second >= 3 {
        return "\(second) seconds ago"
    }
    
    if let year = components.year, year < 0 {
        if(abs(year) == 1){
            return "\(abs(year)) year to go"}
        else{
            return "\(abs(year)) years to go"}
    }
    
    if let month = components.month, month < 0 {
        if(abs(month) == 1){
            return "\(abs(month)) month to go"}
        else{
            return "\(abs(month)) months to go"}
    }
    
//    if let week = components.weekOfYear, week < 0 {
//        if(abs(week) == 1){
//            return "\(abs(week)) week to go"}
//        else{
//            return "\(abs(week)) weeks to go"}
/   }
    
    if let day = components.day, day < 0 {
        if(abs(day) == 1){
            return "\(abs(day)) day to go"}
        else{
            return "\(abs(day)) days to go"}
    }
    
    if let hour = components.hour, hour < 0 {
        if(abs(hour) == 1){
            return "\(abs(hour)) hour to go"}
        else{
            return "\(abs(hour)) hours to go"}
    }
    
    
    if let minute = components.minute, minute < 0 {
        if(abs(minute) == 1){
            return "\(abs(minute)) minute to go"}
        else{
            return "\(abs(minute)) minutes to go"}
    }
    if let sec = components.second, sec < 0 {
        if(abs(sec) == 1){
            return "\(abs(sec)) second to go"}
        else{
            return "\(abs(sec)) seconds to go"}
    }
    
    return "Just now"    
}

Friday, September 15, 2017

Simple URLRequest in objective c

-(void) getPlaces: (NSString *) googleType {

    NSString * newRadius = 100;
    
    NSString *url = [NSString stringWithFormat:@"urlHere?location=%f,%f&radius=%@&types=%@&sensor=true&key=%@", CurrentLat, CurrentLong, newRadius, googleType, kGOOGLE_API_KEY];
    
    //Formulate the string as a URL object.
    NSURL *googleRequestURL=[NSURL URLWithString:url];
    
    
    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    
    dispatch_async(mainQueue, ^{
        
        NSData* data = [NSData dataWithContentsOfURL: googleRequestURL];
        [self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES];
        
    });
    
    
}

-(void)fetchedData:(NSData *)responseData {
    //parse out the json data
    [refreshController endRefreshing];
    HIDE_PROGRESS;
    
    if (responseData == nil) {
        return;
    }
    
    NSError* error;
    NSDictionary* json = [NSJSONSerialization
                          JSONObjectWithData:responseData
                          
                          options:kNilOptions
           
                          error:&error];
    
    NSArray* places ;
        
        if ([[json objectForKey:@"status"] isEqualToString:@"0"]) {
            
        }
        else
        {
          
                
        }

    resultArr = [[NSMutableArray alloc]initWithArray:places];
    
    [_resultTbl reloadData];

    NSLog(@"Google Data: %@", places);

}

API Request Using AFNetworking in swift

API Request Using AFNetworking in swift


import UIKit
import AFNetworking



//import Setting
protocol DataSyncManagerDelegate
{
    func launchObjectSuccess(sender : NSString, andServiceKey:NSString)
    func launchObjectFailure(sender : NSString, andServiceKey:NSString)
}


class DataSyncManager: NSObject {

    //var ServiceUrl:String!
    var ServiceKey:String!
    var delegateDataSync : DataSyncManagerDelegate?
    
    func jsonFailed(error: NSError) {
        print("Error: \(error.localizedDescription)")
        
        delegateDataSync?.launchObjectFailure(sender: error.description as NSString, andServiceKey:ServiceKey as NSString)
    }
    
    func makeGet(place:String)
    {
        let serviceURL = Constants.ServiceURL+ServiceKey;
        
        let manager = AFHTTPSessionManager()
        manager.requestSerializer = AFJSONRequestSerializer()
        manager.responseSerializer = AFHTTPResponseSerializer()
        manager.requestSerializer.setValue(Constants.SecureKey, forHTTPHeaderField: "API-KEY")
        manager.get(serviceURL, parameters: nil, progress: nil, success:
            {
                requestOperation, response in
                
                let result = NSString(data: (response as! NSData) as Data, encoding: String.Encoding.utf8.rawValue)!
                self.delegateDataSync?.launchObjectSuccess(sender: result, andServiceKey:self.ServiceKey as NSString)
                
            }, failure: {
                requestOperation, error in
                
                self.delegateDataSync?.launchObjectFailure(sender: error.localizedDescription as NSString, andServiceKey:self.ServiceKey as NSString)
        })
        
    }
    
    
    func makePOST(ServiceUrl : String, place : String, param : NSMutableDictionary)
    {
        let serviceURL =  ServiceUrl+place;
        DispatchQueue.global(qos: .background).async {
            print("This is run on the background queue")
        let manager = AFHTTPSessionManager()
        manager.requestSerializer = AFJSONRequestSerializer()
        manager.responseSerializer = AFHTTPResponseSerializer()
        manager.requestSerializer.setValue(Constants.SecureKey, forHTTPHeaderField: "API-KEY")
        manager.post(serviceURL, parameters: param, progress: nil, success:
            {
                requestOperation, response in
            
                let result = NSString(data: (response as! NSData) as Data, encoding: String.Encoding.utf8.rawValue)!
               // self.HandleServiceSuccess(result: result, serviceKey: self.ServiceKey as NSString, input: param)
                self.delegateDataSync?.launchObjectSuccess(sender: result, andServiceKey:self.ServiceKey as NSString)
            
        },
        failure:
            {
                requestOperation, error in
                 self.HandleServiceFailure(error: error.localizedDescription as NSString, serviceKey: self.ServiceKey as NSString)
                
                print("Service Error, Service :", place, ",Message :", error.localizedDescription as NSString)
        })
            
        }
        DispatchQueue.main.async {
            print("This is run on the main queue, after the previous code in outer block")
            
        }

    }
    
    func HandleServiceSuccess(result : NSString, serviceKey:NSString, input:NSMutableDictionary)
    {
        
        if serviceKey.isEqual(Constants.kLoginUser)
        {
            let dict : NSMutableDictionary = self.convertStringToDictionary(text: result as String)
            print(dict)
            if(dict.allKeys.count > 0)
            {
                print("Output for :", Constants.kLoginUser, dict)
                let status : NSString = dict.value(forKey: "Status") as! NSString
                if status .isEqual(to: "Success")
                {
                }
                else
                {
                    print(dict.value(forKey: "Message") as! String)
                    
                }
            }
            else
            {
            }
        }
        else
        {
            self.delegateDataSync?.launchObjectSuccess(sender: result, andServiceKey:serviceKey as NSString)
        }
        
    }
    
    
    func HandleServiceFailure(error : NSString, serviceKey:NSString)
    {
        if serviceKey .isEqual(Constants.kLoginUser)
        {
            self.delegateDataSync?.launchObjectFailure(sender: error as NSString, andServiceKey:serviceKey as NSString)
            print(serviceKey , error)
        }
        else
        {
            self.delegateDataSync?.launchObjectFailure(sender: error as NSString, andServiceKey:serviceKey as NSString)
        }
        
        
        
    }
    

    func convertStringToDictionary(text: String) -> NSMutableDictionary
    {
        var json = NSMutableDictionary()
        if let data = text.data(using: String.Encoding.utf8) {
            do {
                json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! NSMutableDictionary
                return json
            } catch {
                print("Something went wrong")
            }
        }
        return json

    }
}

UICollectionView In swift

UICollectionView in Swift

var cvMenu:UICollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: UICollectionViewFlowLayout.init())

    var layout:UICollectionViewFlowLayout = UICollectionViewFlowLayout.init()


/////Create Frame
cvMenu = UICollectionView(frame: CGRect (x: 5, y: 0, width: Constants.ScreenWidth-10, height: Constants.ScreenHeight-130), collectionViewLayout: layout)
        cvMenu.dataSource = self
        cvMenu.delegate = self
//Register Nib File if custom nib
        let nibName = UINib(nibName: "CVDashboard", bundle:nil)
        cvMenu.register(nibName, forCellWithReuseIdentifier: "CVCell");
        cvMenu.showsVerticalScrollIndicator = false
        cvMenu.backgroundColor = UIColor.clear;
        self.addSubview(cvMenu)

//MARK: - Collection View Delegates
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 10;
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CVCell", for: indexPath as IndexPath)
        cell.backgroundColor = colorMenu.object(at: indexPath.row) as? UIColor
        let lblTitle:UILabel = (cell.viewWithTag(101) as? UILabel)!
            
        return cell
    }
    
    func collectionView(_ collectionView : UICollectionView,layout collectionViewLayout:UICollectionViewLayout,sizeForItemAtIndexPath indexPath:NSIndexPath) -> CGSize
    {
        // let cellSize:CGSize = CGSize(250 250);
        let cellWidth:Float = Float((cvMenu.frame.size.width-10)/2);
        let cellHeight:Float = Float(cellWidth/4*2.5);
        
        if (indexPath.row == 4) {
            return CGSize(width: Int(cvMenu.frame.size.width), height: Int(cellHeight))
        }
            
        else {
            return CGSize(width: Int(cellWidth), height: Int(cellHeight))
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForItemAt indexPath: IndexPath) -> UIEdgeInsets {
        //return UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
        return UIEdgeInsetsMake(0, 10, 0, 10);
        
    }

UITableView in swift


UITableView in swift

//Create Table View

var myTable = UITableView()
        myTable.frame = CGRect(x: 0, y: 0, width: Int(Constants.ScreenWidth), height: Int(Constants.ScreenHeight-130))
        myTable.delegate = self
        myTable.dataSource = self
        myTable.backgroundColor = UIColor.white
        myTable.separatorColor = UIColor.clear
        self.view.addSubview(myTable)

//Table view delegate and datasources methods
//MARK: - Table view Delegate -
    func numberOfSections(in tableView: UITableView) -> Int {
        // Return the number of sections.
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // Return the number of rows in the section.
        return 10;
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 68
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        myTable.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        var cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell")! as UITableViewCell
        cell  = UITableViewCell.init(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
        cell.layer.shouldRasterize = true
        cell.layer.rasterizationScale = UIScreen.main.scale
        cell.selectionStyle = UITableViewCellSelectionStyle.none
        
        let backView:UIView = UIView(frame: CGRect(x: 5, y: 0, width: Constants.ScreenWidth-10, height: 63))
        backView.layer.shadowColor = UIColor.lightGray.cgColor;
        backView.layer.shadowOpacity = 0.2;
        backView.layer.shadowOffset = CGSize(width: 2.0, height: 2.0)
        backView.layer.shadowRadius = 0.0;
        backView.backgroundColor = UIColor.white;
        backView.layer.borderWidth = 0.2;
        backView.layer.cornerRadius = 5;
        backView.layer.borderColor = UIColor.lightGray.cgColor;
        cell.contentView.addSubview(backView);
                
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }


Upload UIImage as base64 String

Upload UIImage as Base64 String (Upload UIImage as string) //Select Pic From Camera or Gallery       @objc func btnPro...