2016-10-25 15 views
0

這就是我的工作我的第一個應用程序。筆者對登錄調用函數API網址。而當我輸入用戶名,密碼。它會生成一個客戶ID。而我需要保存的是,我必須使用該特定的ID爲我的所有屏幕,直到用戶註銷。未能與API調用來登錄並不能保存訪問ID

但是,當我在做什麼API調用登錄。它不工作。請幫助我。

這是我的參數傳遞:

{ 
    "username" : "[email protected]", 
    "password" : "u123" 
} 

登錄API調用後,我的JSON輸出:

{ 
    "status": 1, 
    "message": "Login success.", 
    "CustomerDetails": { 
    "CustomerId": "1", 
    "CustomerName": "u", 
    "CustomerEmail": "[email protected]", 
    "CustomerMobile": "901", 
    "CustomerAddress": "#45, 7th main road." 
    } 
} 

在這方面,我需要保存CustomerId,我必須使用CustomerId我所有的屏幕。

我的API調用機能的研究,同時登錄按鈕,輕按:

func getcartdetaildata() { 
     let headers = [ 
      "cache-control": "no-cache", 
      "postman-token": "4c933910-0da0-b199-257b-28fb0b5a89ec" 
     ] 

     let jsonObj:Dictionary<String, Any> = [ 

       "username" : "\(UsernameEmail)", 
       "password" : "\(Password)" 

     ] 


     if (!JSONSerialization.isValidJSONObject(jsonObj)) { 
      print("is not a valid json object") 
      return 
     } 

     if let postData = try? JSONSerialization.data(withJSONObject: jsonObj, options: JSONSerialization.WritingOptions.prettyPrinted) { 
      let request = NSMutableURLRequest(url: NSURL(string: "http://Login.php")! as URL, 
               cachePolicy: .useProtocolCachePolicy,timeoutInterval: 10.0) 
      request.httpMethod = "POST" 
      request.allHTTPHeaderFields = headers 
      request.httpBody = postData 

      let session = URLSession.shared 
      let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in 
       if (error != nil) { 
        ///print(error) 
       } else { 

        print("123.......... ") 

        DispatchQueue.main.async(execute: { 

         if let json = (try? JSONSerialization.jsonObject(with: data!, options: [])) as? Dictionary<String,AnyObject> 
         { 

          print(json) 

          let status = json["status"] as? Int; 
          if(status == 1) 
          { 
           print("asdasdasx.......... ") 

           // let access_token = json["CustomerId"] 

           //print(access_token) 
           DispatchQueue.main.async(execute: { 

//          
//          
//         //Set logged in to true 
//         UserDefaults.standard.set(true, forKey: "ISLOGGEDIN") 
//          
//         //Set access token 
//         UserDefaults.standard.setValue(access_token, forKey: "CustomerId") 
//          
//         UserDefaults.standard.synchronize() 
//          


            }) 

          } 
         } 
        }) 
       } 
      }) 

      dataTask.resume() 
     } 
    } 

請幫助我。

感謝

+0

Retriving數據爲什麼要使用2次DispatchQueue? –

+0

Measn that ???。我應該刪除任何1 – jeo

+0

什麼是不工作;我的意思是什麼錯誤? – PrafulD

回答

0
func apicalling() { 

    let Username:NSString = EmailTextField.text! as NSString 
    let password:NSString = PasswordTextField.text! as NSString 

    let headers = [ 
     "content-type": "application/json", 
     "cache-control": "no-cache", 
     "postman-token": "4c933910-0da0-b199-257b-28fb0b5a89ec" 
    ] 
    let parameters = [ 
      "username": "\(Username)", 
      "password": "\(password)" 
    ] 
    do { 
     let postData = try JSONSerialization.data(withJSONObject: parameters, options :[]) 
     let request = NSMutableURLRequest(url: NSURL(string: "http://Login.php")! as URL,cachePolicy: .useProtocolCachePolicy,timeoutInterval: 10.0) 
     request.httpMethod = "POST" 
     request.allHTTPHeaderFields = headers 
     request.httpBody = postData 

     let session = URLSession.shared 
     let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in 
      if (error != nil) { 
       ///print(error) 
      } else { 

      DispatchQueue.main.async(execute: { 

      if let json = (try? JSONSerialization.jsonObject(with: data!, options: [])) as? Dictionary<String,AnyObject> 
        { 
         let status = json["status"] as? Int; 
         if(status == 1) 
         { 
          print(json) 
          } 

        } 
       }) 
      } 
     }) 

     dataTask.resume() 



    } catch { 
     // print("JSON serialization failed: \(error)") 
    } 
} 

代碼保存在數據NSUserDefaults的。

let userDefaults = NSUserDefaults.standardUserDefaults() 
userDefaults.setValue(YOUR_VALUE, forKey: "PASSKEY") 
userDefaults.synchronize() // don't forgot this line  

NSUserDefaults的從

if let VARIABLE = userDefaults.valueForKey("PASSKEY") { 
    // do something here when a Data exists 
} 
else { 
    // no data exists 
} 
+0

我可以通過這樣的參數'let參數= [ 「用戶名」:「\(emailfield!.text)」, 「password」: 「\(passwordField!的.text)」 ]'如果我給任何靜態數據的給予狀態= 1。但是,如果我傳遞值參數的動態顯示不正確的狀態 – jeo

+0

還有一兩件事。你提供了一些解決方案,將用戶ID保存在userdefault中。但是,我怎麼能通過該或在其他屏幕或其他類中使用保存的nsuserdefault客戶ID – jeo

+0

例如,在我的主屏幕中,我需要將此客戶ID傳遞給api。那麼我怎麼能通過這個保存的nsuser默認客戶ID。而我怎麼能在其他vc類別中調用 – jeo