Thursday, September 13, 2018

Replace occurrences of space in URL

Some time developer face issue to validate or perfect in URL below code help you create a correct URL.

I want to replace the spaces with '%20'.


The correct format for replacing space from url is :
Objective C
NSString *urlString;//your url string.

urlString = [originalUrl stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
or
urlString = [originalUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
iOS 9 and later
urlString = [originalUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
Swift :
var originalUrl = "https://google.co.in"
var urlString :String = originalUrl.stringByReplacingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
ios 9 and later
var urlString :String = originalUrl.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
Swift 4
var urlString = originalString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)

Friday, August 10, 2018

Swift 3.0  Post Local Notification

Notification name should be same for both sender and receiver

// Some where in class A [Post (Broadcast)]

let notificationObjName = Notification.Name("NotificationName")
NotificationCenter.default.post(name: notificationObjName, object: nil)


// And in other class B register for notification

let notificationName = Notification.Name("NotificationName")
NotificationCenter.default.addObserver(self, selector: #selector(ClassB.methodName), name: notificationName, object: nil)

// This method is call when post notification in Class B
func methodName(notification: NSNotification) {
        // Do, what you want
    }



Pass data using notification

let tempDict:[String: UIImage] = ["image": image]

// post a notification with data to class A
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: tempDict)
        
// Register to receive notification in your class B
NotificationCenter.default.addObserver(self, selector: #selector(classB.methodName(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)

// recive notification
func methodName(_ notify: NSNotification) {        
    if let image = notify.userInfo?["image"] as? UIImage {
       // Do, what you want
     }
}










Swift 3.0 - Check if array contains element with property 

if array.contains(where: { $0.someProperty == "matchProperty" }) {
     // Property found
} else {
    // Property not found
}


    let elements = [1, 2, 3, 4, 5]
    if elements.contains(5) { 
        // Found
      } else {
         // Not Found
      }

Saturday, June 30, 2018


If no Simulator showing in xcode try this



I could not find any solution that would fix my issue. All simulators were there for all projects but the one that I needed them.
Solution:
Build Settings -> Architectures -> Supported Platforms:
changed from iphoneos to iOS

xcode : 9.3


Sunday, July 10, 2016

UIImage from a UIColor

Many time graphic team are very busy and they are not able to provide single color image or background for my controller. So, I do google and found  Below code help me to convert UIColor to UIImage.

In Objective-c 

+ (UIImage *)imageFromColor:(UIColor *)color {
    CGRect rect = CGRectMake(0, 0, 1, 1);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
UIImage *img = [YourClassName imageFromColor:[UIColor blueColor]];

In Swift 2.0

extension UIImage {
    static func fromColor(color: UIColor) -> UIImage {
        let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()
        CGContextSetFillColorWithColor(context, color.CGColor)
        CGContextFillRect(context, rect)
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return img
    }
}  
let img = UIImage.fromColor(.blueColor())

For alpha replace 
UIGraphicsBeginImageContext(rect.size);
With
UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);



























Saturday, July 2, 2016


Using a dispatch_once create a Singleton model in Swift

The traditional Objective-C approach in Swift to create a Singleton model.

One of the toughest issues to debug is the one created by the multiple instances of a class which manages the state of a single resource. It is highly desirable if we can use some Design Pattern to control the access to that shared resource. The Singleton pattern fits the bill perfectly to solve this scenario; by wrapping a singleton class around this problem ensures that there will be only one instance of the class at any given time. A most common and clichéd example for a singleton class is the one used for logging purposes where the whole application needs only one logger instance at anytime

If you opt for the lazy instantiation paradigm, then the singleton variable will not get memory until the property or function designated to return the reference is first called. This type of instantiation is very helpful if your singleton class is resource intense.




class Global: NSObject {

    var arrayDaysName: NSMutableArray! = []

    class var sharedInstance : Global {
        struct Static {
            static var onceToken : dispatch_once_t = 0
            static var instance : Global? = nil
        }
        dispatch_once(&Static.onceToken) {
            Static.instance = Global()
        }
        return Static.instance!

    }

}

How to use?, It simple
Global.sharedInstance.arrDaysForecast = //Do what you want

Thursday, June 23, 2016

Create Custom Cell Using XIB With Protocol(Call back method) in swift

I will show you how to customize table view cells by using static xib and by subclassing UITableViewCell in Swift.

Create a Empty project and next create a subclass with xib named by CustomTableCell.
In next three screen follow the code(don't forgot delegate 'CustomTableCellDelegate') and design the xib.

Also create a uibutton action

In your viewcontroller implement cell delegate and tableview datasource and delegate also
and follow the screens

if you create a cell without Register cell close 'option 1' and open 'option 2' codes


And in viewcontroller xib 


every thing is done now just run your project