Thursday, 27 April 2017

Alamofire

Step :1 Install Pod

pod 'AlamofireSwiftyJSON'

pod 'SwiftyStoreKit'

Step :2 Import
import Alamofire

Step: 3
import .pch file
uikit and other framwork

Step 4:

Api with parm ******

 let APISTRingURL: String = "api"
     
        let credentialData = "\(auth)".data(using: String.Encoding.utf8)!
        let base64Credentials = credentialData.base64EncodedString() //base64EncodedStringWithOptions([])
        let headers = ["Authorization": "Basic \(base64Credentials)"]
     
        let param = [
            "user_id":"\(selectlangid)"
        ]
     
        print(param)
     
        Alamofire.request(APISTRingURL, method: .post, parameters: param, headers: headers).validate().responseJSON { (response) in
            print(response.result.value ?? AnyObject.self)
         
            guard response.result.error == nil else {
                // got an error in getting the data, need to handle it
                print("error calling POST on /todos/1")
                print(response.result.error!)
                 self.showAlert(message: "Please chack internet connection.")
                return
            }
            // make sure we got some JSON since that's what we expect
            guard let json = response.result.value as? [String: Any] else {
                print("didn't get todo object as JSON from API")
                print("Error: \(response.result.error)")
                return
            }
         
            print(json)
            // get and print the title
            guard let status = json["status"] as? Int else {
                print("Could not get todo title from JSON")
                return
            }
         
         
         
            let responsesss = json as NSDictionary
         
            print(responsesss)
            self.HUD.isHidden=true
         
            if status == 1
            {
                var temparay:NSArray = NSArray()
                temparay =  responsesss.value(forKey: "category_list") as! NSArray
             
                   
            }
            else
            {
             
            }
        }

********************************************************************
without parem

 let newTodo: [String: Any] = [:] insted param
*******************************************************************
Image upload
**********************************
 HUD.isHidden=false
                HUD.show(animated: true)
               
                let APISTRingURL: String = "\(APISTR)signup/postdata/format/json"
               
                let credentialData = "\(AUTHSTR)".data(using: String.Encoding.utf8)!
                let base64Credentials = credentialData.base64EncodedString() //base64EncodedStringWithOptions([])
                let headers = ["Authorization": "Basic \(base64Credentials)"]
               
                //cat_id  subcat_id offset, tag_id, user_id
               
                let param = [
                    "user_name":fnameTF.text!,
                    "email":emailTF.text!,
                    "password":passTF.text!,
                    "phone":phoneTF.text!
                   
                ]
               
                print(param)
                Alamofire.upload(
                    multipartFormData: { MultipartFormData in
                       
                        for (key, value) in param {
                            MultipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
                        }
                        let imageData = UIImagePNGRepresentation(self.profileIMG.image!)
                       
                        MultipartFormData.append(UIImageJPEGRepresentation(UIImage(data: imageData!)!, 1)!, withName: "user_photo", fileName: "swift_file.jpeg", mimeType: "image/jpeg")
                       
                       
                       
                }, to: APISTRingURL,headers:headers) { (result) in
                   
                    switch result {
                    case .success(let upload, _, _):
                       
                        upload.responseJSON { response in
                            //print(response.result.value)
                           
                            self.HUD.isHidden=true
                            let dic=response.result.value as! NSDictionary
                            let status=dic.value(forKey: "status") as! Int
                            print(dic)
                           
                            if status == 1
                            {
                                let msg = dic.value(forKey: "message") as! String

                               self.navigationController!.popViewController(animated: true)
                               
                                let custdetaildic=dic.value(forKey: "user_detail") as! NSDictionary
                                print(custdetaildic)
                                let custdet=custdetaildic.mutableCopy() as! NSMutableDictionary
                                UserDefaults.standard.setValue(custdet, forKey: "smartstylelogindetail")
                               
                                let logid=custdet.value(forKey: "user_id") as! String
                                UserDefaults.standard.setValue(logid, forKey: "SSUserID")
                                UserDefaults.standard.set(true, forKey: "SSuserLogin")
                               
                                let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
                                let viewController = mainStoryboard.instantiateViewController(withIdentifier: "ViewControllersb") as! UINavigationController
                                UIApplication.shared.keyWindow?.rootViewController = viewController;
                                self.title=""
                                self.navigationController!.navigationBar.tintColor = UIColor.white
                               
                            }
                            else
                            {
                                let msg = dic.value(forKey: "message") as! String
                                self.showAlert(message: self.getvalue(message: msg))
 
                            }
                           
                        }
                       
                    case .failure( _): break
                       
                    }
                   
                   
                }
            }



Sunday, 2 April 2017

SDWebImage

https://github.com/rs/SDWebImage

Step :1
Install pod 'SDWebImage', '~>3.8'

Step:2


import SDWebImage


 let url = NSURL(string: userdetail.valueForKey("profile") as! String)
        let placeHolderImage = UIImage.gifWithName("loading165-92")
        profileimg.sd_setImageWithURL(url, placeholderImage:placeHolderImage, completed: { (image, error, cacheType, url) -> Void in
            if (cacheType == SDImageCacheType.None && image != nil) {
                self.profileimg.alpha = 0;
                UIView.animateWithDuration(0.0, animations: { () -> Void in
                    self.profileimg.alpha = 1
                })
            } else {
                self.profileimg.alpha = 1;
            }
        })
     profileimg.layer.cornerRadius=profileimg.frame.size.width/2
      profileimg.clipsToBounds=true
***************************************



let SUBcat_image = UIImageView()
SUBcat_image.isUserInteractionEnabled=true
SUBcat_image.frame=CGRect(x: 5,y: 0,width: WidthofIMG,height: WidthofIMG)
let url = NSURL(string: (self.searcharr.object(at: subcat) as AnyObject).value(forKey: "subcat_image") as! String)
let placeHolderImage = UIImage.sd_animatedGIFNamed("100X100")
 SUBcat_image.sd_setImage(with: url as URL!, placeholderImage:placeHolderImage, completed: { (image, error, cacheType, url) -> Void in
  if (cacheType == SDImageCacheType.none && image != nil) {
         SUBcat_image.alpha = 0;
   UIView.animate(withDuration: 0.0, animations: { () -> Void in
         SUBcat_image.alpha = 1
          })
    } else {
           SUBcat_image.alpha = 1;
            }
       })

 Sub_cointain_View.addSubview(SUBcat_image)

****https://stackoverflow.com/questions/38949214/ambiguous-use-of-sd-setimagewithplaceholderimagecompleted-with-swift-3****



Connection API Call

Step 1:
    var plistconnection:NSURLConnection=NSURLConnection()
    var plistdata:NSMutableData=NSMutableData()

Step 2:
    HUD.hidden=false
            HUD.showAnimated(true)
           
            let loginString = AUTHSTR
            let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
            let base64LoginString = loginData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
           
           
            let url = NSURL(string: "\(APISTR)api/api/favourite/postdata/format/json")
            let request1 = NSMutableURLRequest(URL: url!)
            request1.HTTPMethod = "POST"
           
            let bodyData = "user_id=\(userid)&event_id=\(eventid)&is_fav=1"
            request1.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding)
            request1.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
           
            plistconnection = NSURLConnection(request: request1, delegate: self)!
            plistconnection.start()

Step 3:

/***************************************************/
    // MARK: Connection Method
    /*****************************************************/
    func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
       
        if connection == plistconnection {
           
            plistdata.appendData(data)
           
        }
     
       
    }
    func connection(connection: NSURLConnection!, didReceiveResponse response: NSURLResponse!)
    {
        // Received a new request, clear out the data object
       
       
        if connection == plistconnection {
           
           plistdata.length=0
           
        }
     
       
    }
    func connection(connection: NSURLConnection, didFailWithError connectionData: NSError) {
        HUD.hidden=true
        showAlert(message: "Please check your internet connection")
        return
    }
   
    func connectionDidFinishLoading(connection: NSURLConnection!)
       
    {
       
        if connection == plistconnection
        {
           
            HUD.hidden=true
//            let strdata = String(data: plistdata, encoding: NSUTF8StringEncoding)
//            print(strdata)
            do {
                if let jsonResult = try NSJSONSerialization.JSONObjectWithData(plistdata, options: []) as? NSDictionary {
                    print(jsonResult)
                   
                    let dic = jsonResult as! NSMutableDictionary
                   
                    print(dic)
                   
                    let strsuccess = dic.valueForKey("status") as! Int
                   
                    if strsuccess == 1 {
                       
                       
                        pageno=dic.valueForKey("offset") as! Int
                        let temparr=dic.valueForKey("event_list") as! NSArray
                        let  pagingAry=temparr.mutableCopy() as! NSMutableArray
                        for i in 0 ..< pagingAry.count
                        {
                            popdetailarr.addObject(pagingAry.objectAtIndex(i))
                        }
                        print(popdetailarr)
                        tab.reloadData()
                        tab.hidden=false
                       
                        if popdetailarr.count < 3
                        {
                            self.tab.tableFooterView = UIView(frame: CGRectZero)
                        }
                       
                    }
                    else
                    {
                         self.tab.tableFooterView = UIView(frame: CGRectZero)
//                        let msg = dic.valueForKey("message") as! String
//                        showAlert(message: msg)
                       
                    }
                   
                }
            }catch let error as NSError {
                print(error.localizedDescription)
            }
        }
   
       
    }


Pagging in IOS

 func scrollViewDidScroll(scrollView: UIScrollView){
        var offset:CGFloat,scrollheigt:CGFloat
        offset=(scrollView.contentOffset.y + scrollView.frame.size.height)
        scrollheigt=scrollView.contentSize.height
     
        let offstr = NSString(format: "%.2f", offset)
        let scrollheigtstr = NSString(format: "%.2f", scrollheigt)
        print(scrollheigtstr)
        print(offstr)
        if offstr.isEqualToString(scrollheigtstr as String)
        {
         
            if popdetailarr.count<3
            {
             
            }
            else
            {
             
                self.CallPostListAPI()
            }
        }
    }

++++++++++++++++++++++++++++++++++++++++++++++++++++

 func scrollViewDidScroll(_ scrollView: UIScrollView)
    {
       
        var offset:CGFloat,scrollheigt:CGFloat
       
        offset=(scrollView.contentOffset.y + scrollView.frame.size.height)
        scrollheigt=scrollView.contentSize.height
       
        print(offset)
        print(scrollheigt)
        if offset >= (scrollheigt-20)//offstr.isEqualToString(scrollheigtstr as String)
        {
           
            if ProductARAY.count<50
            {
               
            }
            else
            {
             
                  if is_status == false
                    {
                     self.Main_product_apicall()
                    }
             
             
            }
        }
     
   
       
       
       
    }