2017-04-12 78 views
0

我已經在我的應用程序中爲登錄創建了一個腳本。用戶鍵入他們的用戶名和密碼,然後將這些值發送到服務器。我有一個PHP腳本來檢查數據庫值,然後我返回一個JSON編碼數組回到我的應用程序。我解析結果,將值存儲在userdefaults中,然後進入應用程序。一切都很好,直到我實現了另一個功能從數據庫返回報價。錯誤域= NSCocoaErrorDomain代碼= 3840「沒有值。」

該錯誤是非常奇怪的,因爲它不會發生在每次,但頻率不足以導致問題。我不明白爲什麼


斯威夫特

let myUrl = NSURL(string: "https://www.example.com/scripts/userLogin.php"); 
    let request = NSMutableURLRequest(url:myUrl! as URL) 

    request.httpMethod = "POST"; 
    let postString = "username=\(username)&password=\(password)"; 
    request.httpBody = postString.data(using: String.Encoding.utf8); 

    let task = URLSession.shared.dataTask(with: request as URLRequest){ 
     data, response, error in 

     if error != nil { 
      print("error=\(String(describing: error))") 
      return 
     } 

     // Parse the results of the JSON result and naivigate to app if success 
     var err: NSError? 
     do { 
      let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary 
      if let parseJSON = json { 

       let resultValue:String = parseJSON["status"] as! String; 

        if (resultValue == "Success"){ 

        let storedUserID: String = parseJSON["user_id"] as! String; 
        let storedUsername: String = parseJSON["username"] as! String; 
        let storedFirstname: String = parseJSON["firstname"] as! String; 
        let storedSurname: String = parseJSON["surname"] as! String; 
        let storedUniName: String = parseJSON["uni_name"] as! String; 
        let storedUniCourse: String = parseJSON["uni_course"] as! String; 
        let storedEmail: String = parseJSON["email"] as! String; 
        let storedVerificationCode: String = parseJSON["verification_code"] as! String; 
        let theQuote: String = parseJSON["quote"] as! String 

        let array = [storedUserID, storedUsername, storedFirstname, storedSurname, storedUniName, storedUniCourse, storedEmail, storedVerificationCode, theQuote] 

        UserDefaults.standard.set(array, forKey: "UserDetailsArray"); 
        UserDefaults.standard.set(true, forKey: "isUserLoggedIn"); 
        UserDefaults.standard.synchronize(); 

        print("Successfully logged in with:") 
        print(array) 

        DispatchQueue.main.async{ 
         let mainTabBar = self.storyboard?.instantiateViewController(withIdentifier: "mainTabBar") as! UITabBarController; 
         let appDelegate = UIApplication.shared.delegate as! AppDelegate; 
         appDelegate.window?.rootViewController = mainTabBar 
        } 
       } 
      } 
     } catch let error as NSError { 
      err = error 
      print(err!); 
     } 
    } 
    task.resume(); 

PHP

$check = query_mysql("SELECT * FROM users WHERE username='".$username."'"); 

if ($check->num_rows == 0) { 
    $returnValue["status"] = "Error"; 
    $returnValue["message"] = "No such details found on server"; 
    echo json_encode($returnValue); 
} else { 
    while ($row = $check->fetch_assoc()){ 
     $storedUserID  = $row['user_id']; 
     $storedUsername  = $row['username']; 
     $storedfirstname = $row['firstname']; 
     $storedsurname  = $row['surname']; 
     $storedPass   = $row['password']; 
     $storedUniName  = $row['uni_name']; 
     $storedUniCourse = $row['uni_course']; 
     $storedEmail  = $row['email']; 
     $storedVerificationCode = $row['unique_code']; 
     $verified   = $row['verified']; 
    } 

    if ($storedPass != $password) { 
     $returnValue["status"] = "Failed"; 
     $returnValue["message"] = "The user and password combination do not match"; 
     echo json_encode($returnValue); 

    } elseif ($verified == 0){ 
     $returnValue["status"] = "Unverified"; 
     $returnValue["message"] = "The email associated with this account has not been verified"; 
     echo json_encode($returnValue); 

    } else { 

     // Retrieve a motivational quote 
     $get_quote = query_mysql("SELECT quote FROM study_quotes ORDER BY rand() LIMIT 1"); 

     if (!$get_quote){ 
      $returnValue["quote"] = "Failed"; 
     } else { 
      while ($row = $get_quote->fetch_assoc()) $returnValue["quote"] = $row['quote']; 
     } 

     $returnValue["status"]    = "Success"; 
     $returnValue["user_id"]    = $storedUserID; 
     $returnValue["username"]   = $storedUsername; 
     $returnValue["firstname"]   = $storedfirstname; 
     $returnValue["surname"]    = $storedsurname; 
     $returnValue["uni_name"]   = $storedUniName; 
     $returnValue["uni_course"]   = $storedUniCourse; 
     $returnValue["email"]    = $storedEmail; 
     $returnValue["verification_code"] = $storedVerificationCode; 
     echo json_encode($returnValue); 

數據庫

有一張帶有id和quote的表格(預填充了我自己的數據,用戶無法訪問。我知道有將始終存在,所以我從來不檢查num_rows但只有當查詢失敗行)


使用

我用UserDefaults因爲接下來的屏幕上,我用8號指數(這是報價)設置爲一個標籤爲:

let userDetails: [String] = UserDefaults.standard.stringArray(forKey:"UserDetailsArray")! 
self.quoteLabel.text = userDetails[8] 

我似乎有50%的成功率和50%的失敗率。我將收到錯誤:

Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo={NSDebugDescription=No value.} 
+0

確切的代碼行導致錯誤? – rmaddy

+0

在打印錯誤的底部的swift腳本的catch語句:'catch讓錯誤爲NSError {err =錯誤 print(err!); }' – Nouman

+0

聽起來像你回來壞JSON。當出現錯誤時,使用:String(data:data!,encoding:.utf8)將'data'轉換爲'String'並查看結果是什麼。 – rmaddy

回答

0

感謝rmaddy的幫助。我發現一個似乎工作基本上每次運行該函數,直到返回的數據集不是空的黑客,但我很確定這是不正確的事情,即使它的工作,所以任何幫助仍然將不勝感激:

  } catch let error as NSError { 
      let dataSet = String(data: data!, encoding: .utf8) 

      print("Trying again") 
      if (dataSet?.isEmpty)!{ 
       self.LoginButtonTapped(self) 
      } 

      err = error 
      print(err!); 
     } 
相關問題