Return json value with php from swift iOS

Hello i have a small a problem with the code below, Xcode print this error:

ERROR: json error: Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo={NSDebugDescription=No value.}


SWIFT CODE:


let yourUrl=“mylink.php”

let URL = NSURL(string:yourUrl)

let request:NSMutableURLRequest = NSMutableURLRequest(URL: URL!)

let boundaryConstant = "V2ymHFg03esomerandomstuffhbqgZCaKO6jy";

let contentType = "multipart/form-data; boundary=" + boundaryConstant NSURLProtocol.setProperty(contentType, forKey: "Content-Type", inRequest: request)

let dataString = "Email=\(Email.text)&Password=\(Password.text)"

request.HTTPMethod = "POST"

request.HTTPBody = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)

let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in / / do{

let str = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! [String:AnyObject]

print(str)

} catch {

print("json error: \(error)")


} })


task.resume()



PHP CODE:(mylink.php)

<?php header("Content-Type: application/json"); $email = $_POST["Email"]; $password = $_POST["Password"]; $stat=“myvalue”; return json_encode($stat); ?>

The error you have gotten: Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo={NSDebugDescription=No value.}

is generated when an emtpy data is passed to JSONObjectWithData, which means your php server has sent a response with empty body.


The dev forums are considered to support development for Apple's platforms, so server side development with php seems to be out of scope.


But when an app communicates with HTTP servers, the app needs to simulate web-forms, so having simple checking form would be useful for both client (app) side and server side.

Add this html file to your server and access it through browser. Developer tools of the browser will show you both request and reponse data.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<form method="POST" action="mylink.php">
    Email:<input type="text" name="Email"><br>
    Passowrd:<Input type="password" name="Password"><br>
    <input type="submit" value="submit">
</form>
</body>
</html>

Sorry if I missed it....are you testing with a simulator or a device?

Use ALAMOFIRE 😉

Return json value with php from swift iOS
 
 
Q