Sign up / Login in swift 2.0 Error - swift

Not quite sure what i'm missing here to make this code work. Trying to make an app with login / sign up connecting to a server but i cant seem to get it to work. This is my code :
do {
let post:NSString = "username=\(username)&password=\(password)"
NSLog("PostData: %#",post)
let url:NSURL = NSURL(string: "http://www.ec2-54-191-63-219.us-west-2.compute.amazonaws.com/userRegistration.php")!
let postData:NSData = post.dataUsingEncoding(NSUTF8StringEncoding)!
let request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.HTTPBody = postData
let task = NSURLSession.sharedSession().dataTaskWithRequest(request)
{data, response, error in
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers ) as? NSDictionary
if let parsejson = json
{
let resultValue:String = parsejson["status"] as! String
print("result: \(resultValue)")
if (resultValue == "Success")
{
let alert = UIAlertController(title: "Success", message: "Registration Successful", preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default){action in self.dismissViewControllerAnimated(true, completion: nil)}
alert.addAction(okAction)
self.presentViewController(alert, animated: true, completion: nil)
}
else
{
print(resultValue)
}
}
} catch {
print("failed: \(error)")
}
}
task.resume()
this is the error i get when i try and add an account:
PostData: username=Optional("josh")&password=Optional("test")
fatal error: unexpectedly found nil while unwrapping an Optional value

The error message says it all, you are derefencing a nil data value, likely data in the line JSONObjectWithData(data!, ..., but it should be obvious from where the debugger stops. guard against the error, and go upstream from that.
if error != nil { handle error and abort }
... etc

Related

iOS swift 3.0 Json parsing and alert issue

I'm working on login form. I'm a fresher on iOS development.
After successful login, I want to show an alert after completion of json parsing. I've parsed Ngoid inside a do while block. Now I want to pass the value "Ngoid" to the next view controller so that it can be used to fetch the further data.
Main Problem: Here is the code I have written and it gives me error to write alert it on main thread only.
As I want the "Ngoid" value for further use there, so how should I write it and what is the correct way to execute the code?
Here is the code I have written:
#IBAction func loginbutton(_ sender: Any) {
let myUrl = NSURL(string: "http://www.shreetechnosolution.com/funded/ngo_login.php")
let request = NSMutableURLRequest(url:myUrl! as URL)
request.httpMethod = "POST"// Compose a query string
let postString = "uname=\(textfieldusername.text!)&password=\(textfieldpassword.text!)";
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest){ data , response , error in
if error != nil
{
//let alert = UIAlertView()
let alert = UIAlertController(title: "Alert Box !", message: "Login Failed", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
return
}
// You can print out response object
print("*****response = \(String(describing: response))")
let responseString = NSString(data: data! , encoding: String.Encoding.utf8.rawValue )
if ((responseString?.contains("")) == nil) {
print("incorrect - try again")
let alert = UIAlertController(title: "Try Again", message: "Username or Password Incorrect", preferredStyle: .alert)
let yesAction = UIAlertAction(title: "Nochmalversuchen", style: .default) { (action) -> Void in
}
// Add Actions
alert.addAction(yesAction)
// Present Alert Controller
self.present(alert, animated: true, completion: nil)
}
else {
print("correct good")
}
print("*****response data = \(responseString!)")
do {
//create json object from data
if let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary {
if let email = json["UserName"] as? String,
let password1 = json["passowrd"] as? String {
print ("Found User id: called \(email)")
}
let msg = (json.value(forKey: "message") as! NSString!) as String
let id = (json.value(forKey: "NgoId") as! NSString!) as String
// let alert : UIAlertView = UIAlertView(title: "Alert box!", message: "\(msg!).",delegate: nil, cancelButtonTitle: "OK")
// alert.show()
self.alert = UIAlertController(title: "Alert Box!", message: "\(msg)", preferredStyle: .alert)
print("the alert\(self.alert)")
self.action = UIAlertAction(title: "OK", style: .default) { (action) -> Void in
let viewControllerYouWantToPresent = self.storyboard?.instantiateViewController(withIdentifier: "pass1") as! ViewControllerngodetails
viewControllerYouWantToPresent.temp1 = self.id
self.present(viewControllerYouWantToPresent, animated: true, completion: nil)
}
self.alert.addAction(self.action)
self.present(self.alert, animated: true, completion: nil)
}
}catch let error {
print(error)
}
}
task.resume()
}
A pro tip:
All your UI related tasks need to be done in the main thread. Here you are presenting the alert inside a closure which executes in a background thread, thats the problem. You need to call the main queue and present alert in that block.
EDIT:
Just put your alert code in this-
For Swift 3-
Get main queue asynchronously
DispatchQueue.main.async {
//Code Here
}
Get main queue synchronously
DispatchQueue.main.sync {
//Code Here
}
Every UI update has to be on main thread:
#IBAction func loginbutton(_ sender: Any) {
let myUrl = NSURL(string: "http://www.shreetechnosolution.com/funded/ngo_login.php")
let request = NSMutableURLRequest(url:myUrl! as URL)
request.httpMethod = "POST"// Compose a query string
let postString = "uname=\(textfieldusername.text!)&password=\(textfieldpassword.text!)";
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest){ data , response , error in
if error != nil
{
DispatchQueue.main.async {
let alert = UIAlertController(title: "Alert Box !", message: "Login Failed", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
// Present Alert Controller
self.present(alert, animated: true, completion: nil)
}
return
}
// You can print out response object
print("*****response = \(String(describing: response))")
let responseString = NSString(data: data! , encoding: String.Encoding.utf8.rawValue )
if ((responseString?.contains("")) == nil) {
print("incorrect - try again")
DispatchQueue.main.async {
let alert = UIAlertController(title: "Try Again", message: "Username or Password Incorrect", preferredStyle: .alert)
let yesAction = UIAlertAction(title: "Nochmalversuchen", style: .default) { (action) -> Void in }
// Add Actions
alert.addAction(yesAction)
// Present Alert Controller
self.present(alert, animated: true, completion: nil)
}
}
else {
print("correct good")
}
print("*****response data = \(responseString!)"
do {
//create json object from data
if let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary {
if let email = json["UserName"] as? String,
let password1 = json["passowrd"] as? String {
print ("Found User id: called \(email)")
}
let msg = (json.value(forKey: "message") as! NSString!) as String
let id = (json.value(forKey: "NgoId") as! NSString!) as String
DispatchQueue.main.async {
self.alert = UIAlertController(title: "Alert Box!", message: "\(msg)", preferredStyle: .alert)
print("the alert\(self.alert)")
self.action = UIAlertAction(title: "OK", style: .default) { (action) -> Void in
let viewControllerYouWantToPresent = self.storyboard?.instantiateViewController(withIdentifier: "pass1") as! ViewControllerngodetails
viewControllerYouWantToPresent.temp1 = self.id
self.present(viewControllerYouWantToPresent, animated: true, completion: nil)
}
self.alert.addAction(self.action)
self.present(self.alert, animated: true, completion: nil)
}
}
}catch let error {
print(error)
}
}
task.resume()
}

i got this error objc[17272]: Class PLBuildVersion is implemented in both

This is the code i am about to post a data into my website page but i got this error:
objc[17272]: Class PLBuildVersion is implemented in both
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/System/Library/PrivateFrameworks/AssetsLibraryServices.framework/AssetsLibraryServices
(0x1193af998) and
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/System/Library/PrivateFrameworks/PhotoLibraryServices.framework/PhotoLibraryServices
(0x1191d4d38). One of the two will be used. Which one is undefined.
ERROR
/BuildRoot/Library/Caches/com.apple.xbs/Sources/VectorKit_Sim/VectorKit-1230.31.8.23.3/GeoGL/GeoGL/GLCoreContext.cpp
1763: InfoLog SolidRibbonShader: ERROR
/BuildRoot/Library/Caches/com.apple.xbs/Sources/VectorKit_Sim/VectorKit-1230.31.8.23.3/GeoGL/GeoGL/GLCoreContext.cpp
1764: WARNING: Output of vertex shader 'v_gradient' not read by
fragment shader
func senddata(_ submit:String, username:String,password:String, email:String, jobtype:String, pay:String){
let myUrl = URL(string: "http://localhost/halloffame/php/senddata.php");
let request = NSMutableURLRequest(url:myUrl!);
request.httpMethod = "POST";
let postString = "submit=\(submit)&jobtype=\(jobtype)&pay=\(pay)";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { (data:Data?, response:URLResponse?, error:NSError?) -> Void in
DispatchQueue.main.async
{
// if there is an error throw an alert message
if(error != nil)
{
//Display an alert message
let myAlert = UIAlertController(title: "Alert", message: "something wrong", preferredStyle: UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler:nil)
myAlert.addAction(okAction);
self.present(myAlert, animated: true, completion: nil)
return
}
// get feedback from the website
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
// if status is 200
let status = parseJSON["status"] as? String
if(status! == "200")
{
// show the result of the data
let status = parseJSON["status"]
}else {
// display an alert message
let myAlert = UIAlertController(title: "Alert", message: status, preferredStyle: UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler:nil)
myAlert.addAction(okAction);
self.present(myAlert, animated: true, completion: nil)
}
} // end of parseJSON
} catch
{
print(error)
}
}// dispatch
} as! (Data?, URLResponse?, Error?) -> Void).resume() // nsurlsession
the source is the last line of the code, i tried to delete the line as! (Data?, URLResponse?, Error?) -> Void) but XCODE give me error and suggested to add it back again. if i build a simulator with the code it show no problem until i call the function, then it freeze and gave me this error. this does not happen in swift 2 but only happen once i upgrade.
I had a similar error in an iPhone app i'm working on. Resetting the iOS simulator fixed it for me. Simulator -> Reset Content And Settings.
i found the solution:
in
let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { (data:Data?, response:URLResponse?, error:NSError?) -> Void in
DispatchQueue.main.async
i change it into
let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
DispatchQueue.main.async
then i delete the data,response,error in the bottom
from this
} as! (Data?, URLResponse?, Error?) -> Void).resume() // nsurlsession
into this
}).resume() // nsurlsession

rare issue with a Video downloaded and played in iPad or iPhone

I developed an application and one of the functionalities is to see a video that I downloaded from a server. I'm using Alamofire to access the network, this is my code:
func GetVideoFiedMedia(videoFiedData: VideofiedVideo?, completionHandler: (NSURL?, NSError?) -> ()) {
var result: NSURL? = nil;
let parameters : [ String : AnyObject] = [
"CnxID": (videoFiedData?.cnxID!)!,
"TaskNum": (videoFiedData?.taskNum!)!,
"Ev_File": (videoFiedData?.evFile!)!
]
let headers = [
"Content-Type": "application/json"
]
let urlAux = "https://xxxxxx/xxxxx/xxxxx.svc/VideoMedia?";
Alamofire.request(.POST, urlAux, parameters: parameters, headers: headers, encoding: .JSON)
.validate()
.responseString { response in
switch response.result {
case .Success:
if let JSON = response.result.value {
do{
let data: NSData = JSON.dataUsingEncoding(NSUTF8StringEncoding)!
let decodedJson = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves) as! NSDictionary
let dObj = decodedJson["d"] as! NSDictionary;
let resultSet = dObj["Media"] as? NSArray;
if(resultSet != nil){
let stringsData = NSMutableData();
for item in resultSet! {
let byte = item as! Int;
var char = UnicodeScalar(byte);
stringsData.appendBytes(&char, length: 1)
}
var destinationUrl: NSURL? = nil;
let documentsUrl = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first! as NSURL;
let fileName = "msavid.mp4";
destinationUrl = documentsUrl.URLByAppendingPathComponent(fileName)
let fileMangr = NSFileManager.defaultManager()
var fileHandle = NSFileHandle.init(forWritingAtPath: (destinationUrl?.path!)!)
if(fileHandle == nil){
fileMangr.createFileAtPath((destinationUrl?.path!)!, contents: stringsData, attributes: nil)
fileHandle = NSFileHandle.init(forWritingAtPath: (destinationUrl?.path!)!)
}
if(fileHandle != nil){
fileHandle?.seekToEndOfFile();
fileHandle?.writeData(stringsData);
fileHandle?.closeFile();
}
result = destinationUrl;
completionHandler(result, nil);
}
}catch{
result = nil;
completionHandler(result, nil);
}
}
case .Failure(let error):
completionHandler(result, error);
}
}
}
When I got the nsurl for the video I played it in this way:
_ = self.manager.GetVideoFiedMedia(videoFiedItem, completionHandler: { responseObject, error in
if(responseObject != nil){
var sendSegue = false;
self.nsurl = responseObject;
if NSFileManager().fileExistsAtPath(responseObject!.path!) == true {
if(sendSegue == false){
self.performSegueWithIdentifier("sureViewSegue", sender: nil);
self.nsurl = nil;
sendSegue = true;
MBProgressHUD.hideAllHUDsForView(self.view, animated: true);
}
}else{
MBProgressHUD.hideAllHUDsForView(self.view, animated: true)
let alert = UIAlertController(title: "Alert", message: "We have problem to download the media data, please try again later.", preferredStyle: UIAlertControllerStyle.Alert);
alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.Default, handler: nil));
self.presentViewController(alert, animated: true, completion: nil);
}
}else{
MBProgressHUD.hideAllHUDsForView(self.view, animated: true)
let alert = UIAlertController(title: "Alert", message: "We have problem to download the media data, please try again later.", preferredStyle: UIAlertControllerStyle.Alert);
alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.Default, handler: nil));
self.presentViewController(alert, animated: true, completion: nil);
}
})
The segue that I performed push a AVPlayerViewController.
When I was testing the method using the iOS simulator everything seems to work fine, the problem came when I tried to use the functionality in a real device(iPhone or iPad)the video doesn't show up, I got the AVPlayerViewController with this symbol that can't reproduce the video.
Please any help on this, I can't figure out what is causing the problem.
So simple and at the same time unthinkable, just reset the device and erase the copy of the file msavid.mp4 in the phone and it is working.

Tableview works on sim but not on test device

I have no idea whats wrong with this function. I'm calling it in viewdidload and it prints the array as blank when I load it on my phone. When I do it in the simulator it fills the array though. Using ObjectMapper if that helps at all.
func getData() {
let myURLString = "http://meetup.x10host.com/api/get_event.php?radius=15"
let myURL = NSURL(string: myURLString)!
var myCardsArray = [Card]()
let mySession = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
let myDataTask = mySession.dataTaskWithURL(myURL) { (data, response, error) in
guard error == nil else {
let alertController = UIAlertController(title: "No Connection", message:
"Can't connect to database, perhaps turn on your WiFi?", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default,handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
return
}
do {
let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
for someCard in jsonData as! NSArray{
let card = Mapper<Card>().map(someCard)
myCardsArray.append(card!)
self.nameArray.append(card!.titlee!)
self.textArray.append(card!.text!)
self.userArray.append(card!.attending!)
self.latArray.append(card!.latitude!)
self.longArray.append(card!.longitude!)
self.timeArray.append(card!.time!)
self.locTextArray.append(card!.locationText!)
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
}
} catch {
print("There was an error")
}
}
myDataTask.resume()
print(nameArray)
}

How to dismiss a UIAlert with no buttons or interaction in Swift?

I am using a UIAlert to display the string "Loading..." while my iOS application is interacting with a database. Is there any way to pragmatically dismiss it when the action is complete?
code:
let myUrl = NSURL(string: "http://www.test.org/ios.html")
let request = NSMutableURLRequest(URL: myUrl!)
request.HTTPMethod = "POST"
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
if error != nil {
print("Error: \(error)")
}
dispatch_async(dispatch_get_main_queue()) {
self.testLabel.text = "\(responseString!)"
// dismiss sendLoading() UIAlert
}
}
}
task.resume()
self.sendLoading()
sendLoading func:
func sendLoading() {
let alertController = UIAlertController(title: "Loading...", message:
"", preferredStyle: UIAlertControllerStyle.Alert)
self.presentViewController(alertController, animated: true, completion: nil)
}
Thank you
Make your alertController as instance variable and when you need to dismiss it just call
self.dismissViewController(alertController, animated:true, completion: nil)
Edit - Adding code.
In your case code would be like -
let alertController : UIAlertController ?
let myUrl = NSURL(string: "http://www.test.org/ios.html")
let request = NSMutableURLRequest(URL: myUrl!)
request.HTTPMethod = "POST"
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
if error != nil {
print("Error: \(error)")
}
dispatch_async(dispatch_get_main_queue()) {
self.testLabel.text = "\(responseString!)"
// dismiss sendLoading() UIAlert
self.dismissViewController(alertController!, animated:true, completion: nil)
}
}
}
task.resume()
self.sendLoading()
sendLoading func:
func sendLoading() {
alertController = UIAlertController(title: "Loading...", message:
"", preferredStyle: UIAlertControllerStyle.Alert)
self.presentViewController(alertController, animated: true, completion: nil)
}
The UIAlertController have the function dismissViewControllerAnimated(flag: Bool, completion: (() -> Void)?) that according to Apple:
Dismisses the view controller that was presented modally by the view controller.
Then what you need to do is to keep a reference to the UIAlertController as a property in your UIViewController and then dismiss it as you like, something like this:
// instance of the UIAlertController to dismiss later
var alertController: UIAlertController!
func sendLoading() {
self.alertController = UIAlertController(title: "Loading...", message:
"", preferredStyle: UIAlertControllerStyle.Alert)
self.presentViewController(alertController, animated: true, completion: nil)
}
let myUrl = NSURL(string: "http://www.test.org/ios.html")
let request = NSMutableURLRequest(URL: myUrl!)
request.HTTPMethod = "POST"
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) {
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
if error != nil {
print("Error: \(error)")
}
dispatch_async(dispatch_get_main_queue()) {
self.testLabel.text = "\(responseString!)"
// dismiss sendLoading() UIAlert
self.alertController.dismissViewControllerAnimated(true, completion: nil)
}
}
}
task.resume()
self.sendLoading()
I hope this help you.