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...