Monday, 24 September 2018

Upload Image to server in Swift


Upload image to server in Swift 4.1 and Xcode 9.4.1

Here i'm posting only Upload image code.

In this below code you need to replace your "image file name and uploaded file name".


Call this function like :  uploadImageOne()


func uploadImageOne(){
        
    let imageData = UIImageJPEGRepresentation(yourImage!, 1.0)//Replace your image
        
    if imageData != nil{
       var request = URLRequest(url: NSURL(string:urlString)! as URL)//Send your URL here
       print(request)

       request.httpMethod = "POST"
            
       let boundary = NSString(format: "---------------------------14737809831466499882746641449")
       let contentType = NSString(format: "multipart/form-data; boundary=%@",boundary)
       //  println("Content Type \(contentType)")
       request.addValue(contentType as String, forHTTPHeaderField: "Content-Type")
            
       var body = Data()
            
       body.append(NSString(format: "\r\n--%@\r\n", boundary).data(using: String.Encoding.utf8.rawValue)!)
       body.append(NSString(format:"Content-Disposition: form-data;name=\"title\"\r\n\r\n").data
                            (using:String.Encoding.utf8.rawValue)!)
       body.append("Hello".data(using: String.Encoding.utf8, allowLossyConversion: true)!)

            
       body.append(NSString(format: "\r\n--%@\r\n", boundary).data(using: String.Encoding.utf8.rawValue)!)
       body.append(NSString(format:"Content-Disposition: form-data;name=\"uploaded_file\";filename=\"image.jpg\"\\r\n").data
                           (using:String.Encoding.utf8.rawValue)!) //Here replace your image name and file name
       body.append(NSString(format: "Content-Type: image/jpeg\r\n\r\n").data(using: String.Encoding.utf8.rawValue)!)
       body.append(imageData!)
       body.append(NSString(format: "\r\n--%@\r\n", boundary).data(using: String.Encoding.utf8.rawValue)!)
            
       request.httpBody = body
            
       let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil     
           else { // check for fundamental networking error
           print("error=\(String(describing: error))")
           SharedClass.sharedInstance.alert(view: self, message: "\(String(describing: error!.localizedDescription))")
           return
        }
                
        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode == 500 {
            SharedClass.sharedInstance.alert(view: self, message: "Server Error")
        } else if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
             print("statusCode should be 200, but is \(httpStatus.statusCode)")
             print("response = \(String(describing: response))")
        }
      
        //This can print your response in string formate        
        let responseString = String(data: data, encoding: .utf8)
         //            let dictionary = data
         //            print("dictionary = \(dictionary)")
         print("responseString = \(String(describing: responseString!))")
                
         do {
             self.response3 = (try JSONSerialization.jsonObject(with: data, options: []) as? [String: AnyObject])!
             print(self.response3)
                    
             if (((self.response3["Response"] as? [String : Any])?["status"]) as! String == "SUCCESS") {
                   let message = (self.response3["Response"] as? [String : Any])?["message"] as? String
                       SharedClass.sharedInstance.alert(view:self, message: message)
              } else {
                    let message = (self.response3["Response"] as? [String : Any])?["message"] as? String
                        SharedClass.sharedInstance.alert(view:self, message: message)
                    }

          } catch let error as NSError {
               print(error)
               print(error.localizedDescription)
          }
       }
            
        task.resume()
            
     }
        

    }

Wednesday, 7 February 2018

Auto property synthesis will not synthesize property 'description' because it is 'readwrite' but it will be synthesized 'readonly' via another property (Type of property 'NSMutableArray *' in class extension does not match property type in primary class)



I created one mutable array variable with the name "description". In this case I'm getting one error and warning like this

Ex:
@property NSMutableArray *description;

War: " Auto property synthesis will not synthesize property 'description' because it is 'readwrite' but it will be synthesized 'readonly' via another property "

Error : " Type of property 'NSMutableArray *' in class extension does not match property type in primary class "

Now I changes my variable name like this

Ex:
@property NSMutableArray *desc;

Now it's gone.

If you still want to use "description"

https://stackoverflow.com/questions/34960068/auto-property-synthesis-will-not-synthesise-property-description-because-it-is?rq=1

Thursday, 1 February 2018

ProjectName-Bridging-Header.h' (No such file or directory)



Error - error opening input file '/Users/development/Downloads/ProjectName/ProjectName/ProjectName-Bridging-Header.h' (No such file or directory)



In your project you don't have bridging-Header.h file, but your project has that path. For this you need to delete that path...
Go to targets file and select -----> Build Settings, 
---->Swift Compiler - General, 
----->and delete the bridging-Header.h. 

Follow below screen shots....

Delete the bridging-Header.h file in Swift Compiler - General


Now you got like this...

Tuesday, 23 January 2018

Google places search/auto complete example

#import "AppDelegate.h"
#import <GoogleMaps/GoogleMaps.h>

@interface AppDelegate ()

@end

@import GooglePlaces;

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    [GMSPlacesClient provideAPIKey:@"Your key here"];

    return YES;
}



#import "ViewController.h"

@interface ViewController () <UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource> {
    
    NSMutableArray *searchArray;
    NSString *strSearch;

}

@property (weak, nonatomic) IBOutlet UITextField *searchTextfeild;
@property (weak, nonatomic) IBOutlet UITableView *tbl_vw1;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    _searchTextfeild.delegate = self;
    _tbl_vw1.delegate = self;
    _tbl_vw1.dataSource = self;
    _tbl_vw1.hidden = YES;
    
    _searchTextfeild.clearButtonMode = UITextFieldViewModeAlways;
    
    //Resize tableview when display keyboard (show keyboard and hide keyboard)
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardShown:) name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardHidden:) name:UIKeyboardDidShowNotification object:nil];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


//When keyboard show
-(void)keyboardShown:(NSNotification *)note {
    CGRect keyboardFrame;
    [[[note userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardFrame];
    CGRect tableViewFrame = _tbl_vw1.frame;
    tableViewFrame.size.height -= keyboardFrame.size.height;
    [_tbl_vw1 setFrame:tableViewFrame];
}

//When keyboard hide
-(void)keyboardHidden:(NSNotification *)note {
    CGFloat maxY = CGRectGetMaxY(_searchTextfeild.frame);
    CGFloat height = CGRectGetHeight(_searchTextfeild.frame);
    height = height+20;
    [_tbl_vw1 setFrame:CGRectMake(0, maxY, self.view.frame.size.width, self.view.frame.size.height-height)];
}


- (void)LoadJson_search{
    
    searchArray=[[NSMutableArray alloc]init];
    
    NSString *str1 = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/autocomplete/json?input=%@&types=geocode&language=fr&key=your key here", strSearch];


    NSURL *url = [NSURL URLWithString:str1];
    
    NSData *data = [NSData dataWithContentsOfURL:url];
    NSError *error=nil;
    if(data.length==0)
    {
        
    }
    else
    {
        NSDictionary *jsondic= [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
        
         NSLog(@"1,,,,%@",jsondic);
        [searchArray removeAllObjects];
        if([[jsondic objectForKey:@"status"]isEqualToString:@"ZERO_RESULTS"])
        {
            
        }
        else if([[jsondic objectForKey:@"status"]isEqualToString:@"INVALID_REQUEST"])
        {
        }
        else
        {
            for(int i=0;i<[jsondic.allKeys count];i++)
            {
                NSString *str1=[[[jsondic objectForKey:@"predictions"] objectAtIndex:i] objectForKey:@"description"];
                [searchArray  addObject:str1];
            }
            _tbl_vw1.hidden = NO;
            NSLog(@"%@", searchArray);
        }
        if (searchArray.count == 0) {
            _tbl_vw1.hidden = YES;
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                [_tbl_vw1 reloadData];
            });
        }
    }
}


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;{
    if (textField.tag == 3) {
        strSearch = [textField.text stringByReplacingCharactersInRange:range withString:string];
        if([string isEqualToString:@" "]){
            
        }else{
            [self LoadJson_search];
        }
    }
    return YES;
}


- (BOOL)textFieldShouldClear:(UITextField *)textField{
    _tbl_vw1.hidden = YES;
    dispatch_async(dispatch_get_main_queue(), ^{
        [_tbl_vw1 reloadData];
    });
    
    return YES;
}


//TableView delegates
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return searchArray.count;
}


-(UITableViewCell *)tableView:(UITableView*)aTableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [_tbl_vw1 dequeueReusableCellWithIdentifier:@"cell"];
    if(!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
//    NSLog(@"searchArray ==== %@", searchArray);
    cell.textLabel.text = [searchArray objectAtIndex:indexPath.row];

    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    _searchTextfeild.text = [searchArray objectAtIndex:indexPath.row];
    
    _tbl_vw1.hidden = YES;
    dispatch_async(dispatch_get_main_queue(), ^{
        [_tbl_vw1 reloadData];
    });
    

}

Difference between == and ===

Difference between == and === https://stackoverflow.com/questions/24002819/difference-between-and == operator checks if their ...