I have 2 application, one in swift and the other in objective-c, I'm using cognito to authenticate with s3 but the last days this feature stop working I down know why, the console of my application say "request timed out" but I don't change anything. the application start uploading but always stops in 39% or 14% and freeze the upload, this is my code:
App delegate:
let credentialsProvider = AWSCognitoCredentialsProvider(regionType:.USEast1,
identityPoolId:poolId)
AWSLogger.defaultLogger().logLevel = .Verbose
let configuration = AWSServiceConfiguration(region:.SAEast1, credentialsProvider:credentialsProvider)
AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = configuration
PhotoViewController
let uploadRequest = AWSS3TransferManagerUploadRequest()
uploadRequest.bucket = "bucket"
uploadRequest.ACL = AWSS3ObjectCannedACL.PublicRead
uploadRequest.key = "\(self.userLogin.customer_subdomain)/photos/\(imageName)"
uploadRequest.contentType = "image/png"
uploadRequest.body = url
uploadRequest.uploadProgress = { (bytesSent:Int64, totalBytesSent:Int64, totalBytesExpectedToSend:Int64) -> Void in
dispatch_sync(dispatch_get_main_queue(), {() -> Void in
self.updateLabel(totalBytesSent,totalBytesExpectedToSend: totalBytesExpectedToSend)
})
}
AWSS3TransferManager.defaultS3TransferManager().upload(uploadRequest).continueWithBlock { (task) -> AnyObject! in
if (task.error != nil) {
//failed
dispatch_async(dispatch_get_main_queue()) {
self.dismissViewControllerAnimated(false, completion: nil)
let refreshAlert = UIAlertController(title: "Error", message: "Error al intentar subir el archivo", preferredStyle: UIAlertControllerStyle.Alert)
refreshAlert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
self.presentViewController(refreshAlert, animated: true, completion: nil)
}
print(task.error!)
} else {
let dic=["file":"\(self.userLogin.customer_subdomain)/photos/\(imageName)"]
let jsonData = try! NSJSONSerialization.dataWithJSONObject(dic, options: [])
let jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)! as String
let con:URLConnection
con=URLConnection.init()
con.delegate=self
let headers=["X-Auth-Token":self.userLogin.api_token]
con.connect(self.userLogin.customer_url+"/rest/activities/\(self.activity.id)/photos",method:"POST",json: jsonString, headers: headers)
self.imgName = "\(self.userLogin.customer_subdomain)/photos/\(imageName)"
}
return nil
}
thank you!
was the datetime of the device, always need to be the correct hour
Related
I have a file download code in my application using AWS Mobile SDK.
That shows an alert with download progress and a cancel button. It is working but I need to cancel download when user hit on alert cancel button. I have tried to cancel the task using the object of AWSS3TransferUtilityDownloadTask and AWSS3TransferUtilityTask.But it seems not working it gives me progress and download completion.
here Is my working code of file download.
Please suggest me how can I Cancel my Download request.
let credentialProvider = AWSStaticCredentialsProvider(accessKey: "MyAccessKey", secretKey: "MySecretKey")
let configuration = AWSServiceConfiguration(region: AWSRegionType.USEast1, credentialsProvider: credentialProvider)
AWSServiceManager.default().defaultServiceConfiguration = configuration
let expression = AWSS3TransferUtilityDownloadExpression()
expression.progressBlock = {(task, progress) in DispatchQueue.main.async(execute: {
// Do something e.g. Update a progress bar.
print("File Progress:",Float(progress.fractionCompleted))
let progress = Float(progress.fractionCompleted)
DispatchQueue.main.async {
if progress == 1.0 {
self.globalAlert.dismiss(animated: true, completion: nil)
}else{
self.globalProgressView!.progress = progress
self.msgProgress = String(Int(progress*100))
}
}
})
}
var completionHandler: AWSS3TransferUtilityDownloadCompletionHandlerBlock?
completionHandler = { (task, URL, data, error) -> Void in
DispatchQueue.main.async(execute: {
// Do something e.g. Alert a user for transfer completion.
// On failed downloads, `error` contains the error object.
//My other code stuff execution
})
}
var refUploadTask: AWSS3TransferUtilityTask?
let transferUtility = AWSS3TransferUtility.default()
transferUtility.downloadData(
fromBucket: Bucket_Name,
key: fileKey,
expression: expression,
completionHandler: completionHandler
).continueWith {
(task) -> AnyObject? in if let error = task.error {
print("Error: \(error.localizedDescription)")
}
if let _ = task.result {
// Do something with downloadTask.
print("download started..")
DispatchQueue.main.async(execute: {
self.globalAlert = UIAlertController(title: "Downloading...", message: "\(String(describing: self.msgProgress))% Completed", preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertAction.Style.default, handler: {
(action : UIAlertAction!) -> Void in
self.refUploadTask.cancel()
})
// Show it to your users
self.globalAlert.addAction(cancelAction)
self.present(self.globalAlert, animated: true, completion: {
// Add your progressbar after alert is shown (and measured)
let margin:CGFloat = 8.0
let rect = CGRect(x: margin, y: 72.0, width: self.globalAlert.view.frame.width - margin * 2.0 , height: 2.0)
self.globalProgressView = UIProgressView(frame: rect)
self.globalProgressView!.tintColor = .blue
self.globalAlert.view.addSubview(self.globalProgressView!)
})
})
}
return nil;
}
You can get the AWSS3TransferUtilityDownloadTask object and cancel the ongoing download.
let awsTask = transferUtility.getDownloadTasks()
if let taskArray = awsTask.result {
for idx in taskArray {
if let task = idx as? AWSS3TransferUtilityDownloadTask {
task.cancel()
}
}
}
This question already has answers here:
How to upload images to a server in iOS with Swift?
(11 answers)
Closed 4 years ago.
I am implementing User Profile Module. For that I want to store the user profile, which user selected from camera or gallery. I want to pass it into the API, but I don't know how to do it.
Below is my code..
var request = URLRequest(url: URL(string: "http://xxxx.xx/UpdateEmp_test?xx=\(xx)&PermanentAddress=\(ADDrEss)&PermVillage=\(townCITY)&PermTaluk=\(taulkcode!)&PermDist=\(districtcode!)&PermPinCode=\(PINcode)&PermState=\(statecode!)&FatherName=\(FatherNaME)&MotherName=\(MothERName)&profile_image=\(imagePath)")!)
print(request)
request.httpMethod = "POST"
let session = URLSession(configuration: .default)
session.dataTask(with: request) {data, response, error in
guard error == nil && data != nil else
{
let alert = UIAlertController(title: "Check your Internet Connection", message: "", preferredStyle: .alert)
self.present(alert, animated: true, completion: nil)
let when = DispatchTime.now() + 3
DispatchQueue.main.asyncAfter(deadline: when)
{
// your code with delay
alert.dismiss(animated: true, completion: nil)
}
return
}
do
{
let json = try JSONSerialization.jsonObject(with: data!, options: [])
print(json)
let message = (json as AnyObject).value(forKey: "message") as! NSString
print(message)
DispatchQueue.main.sync {
if message == "success" {
let alert = CustomAlert(title:"Request Updated Successfully!")
alert.show(animated: true)
self.dismiss(animated: true, completion:nil)
}
else if message == "Already"{
let alert = CustomAlert(title:"Already Request Updated")
alert.show(animated: true)
}
else {
let alert = CustomAlert(title:"Failed,Try Again!")
alert.show(animated: true)
}
}
}
catch
{
}
}.resume()
You can convert the image to Base64 string and sent it to server:
let imageData:NSData = UIImagePNGRepresentation(yourUIImage.image)!
Encoding:
let strBase64 = imageData.base64EncodedString(options: .lineLength64Characters)
Decoding:
let dataDecoded:NSData = NSData(base64EncodedString: strBase64, options: NSDataBase64DecodingOptions(rawValue: 0))!
let decodedimage:UIImage = UIImage(data: dataDecoded)!
yourImageView.image = decodedimage
I try trigger new version available at app store, then i will redirect user to app store. Then inside there i update the app. After finish download, i click open inside app store then my app will open a splash screen then it will auto close. I not get any crash log. This is my code.
DispatchQueue.global().async {
do {
let update = try self.needsUpdate()
print("update",update)
DispatchQueue.main.async {
if update{
self.popupUpdateDialogue();
}
}
} catch {
print(error)
}
}
func popupUpdateDialogue(){
var versionInfo = ""
do {
versionInfo = try self.getAppStoreVersion()
}catch {
print(error)
}
let alertMessage = "Please update this app to version "+versionInfo;
let alert = UIAlertController(title: "New Version Available", message: alertMessage, preferredStyle: UIAlertControllerStyle.alert)
let okBtn = UIAlertAction(title: "Update", style: .default, handler: {(_ action: UIAlertAction) -> Void in
if let url = URL(string: "itms-apps://itunes.apple.com/sg/app/myApp/idxxxx"),
UIApplication.shared.canOpenURL(url){
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
}
})
let noBtn = UIAlertAction(title:"Skip this Version" , style: .destructive, handler: {(_ action: UIAlertAction) -> Void in
})
alert.addAction(okBtn)
alert.addAction(noBtn)
self.present(alert, animated: true, completion: nil)
}
func needsUpdate() -> Bool {
let infoDictionary = Bundle.main.infoDictionary
let appID = infoDictionary!["CFBundleIdentifier"] as! String
let url = URL(string: "http://itunes.apple.com/sg/lookup?bundleId=\(appID)")
let data = try? Data(contentsOf: url!)
let lookup = (try? JSONSerialization.jsonObject(with: data! , options: [])) as? [String: Any]
if let resultCount = lookup!["resultCount"] as? Int, resultCount == 1 {
if let results = lookup!["results"] as? [[String:Any]] {
if let appStoreVersion = results[0]["version"] as? String{
let currentVersion = infoDictionary!["CFBundleShortVersionString"] as? String
if !(appStoreVersion == currentVersion) {
print("Need to update [\(appStoreVersion) != \(currentVersion)]")
return true
}
}
}
}
return false
}
I really dont know why the app will auto terminate/close. I also already checked on this link App Crash when after updating, https://stackoverflow.com/questions/17795920/ios-app-goes-crash-on-startup-after-updating-from-the-app-store,https://stackoverflow.com/questions/15409323/ios-app-cannot-be-opened-after-update but still not get what solution for this issue.
I am trying to pass a users' email address to another ViewController via a delegate when the user has successfully logged in.
The snippet of code in question (marked *) works fine where it is and the data is passed successfully. However, at this point the user has not successfully logged in, therefore I would rather insert the snippet where the /**** is, a little further down.
However it does work when in that position. Why is that? (I am new to Swift)
Thanks
#IBAction func loginButtonTapped(_ sender: AnyObject)
{
let userEmail = userEmailTextField.text;
let userPassword = userPasswordTextField.text;
if (userPassword!.isEmpty || userEmail!.isEmpty) { return; }
// send user data to server side
let myUrl = URL(string: "http://www.quasisquest.uk/KeepScore/userLogin.php");
var request = URLRequest(url:myUrl!);
request.httpMethod = "POST";
let postString = "email=\(userEmail!)&password=\(userPassword!)";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
DispatchQueue.main.async
{
// spinningActivity!.hide(true)
if(error != nil)
{
//Display an alert message
let myAlert = UIAlertController(title: "Alert", message: error!.localizedDescription, preferredStyle: UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler:nil)
myAlert.addAction(okAction);
self.present(myAlert, animated: true, completion: nil)
return
}
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]
*if self.delegate != nil {
self.delegate?.userLoggedIn(data: userEmail! )
}
// retrieve login details and check to see if all ok
if let parseJSON = json {
let returnValue = parseJSON["status"] as? String
if(returnValue != "error")
{
/**** if self.delegate != nil {
self.delegate?.userLoggedIn(data: userEmail! )
} ****/
UserDefaults.set(UserDefaults.standard)(true, forKey: "isUserLoggedIn");
let mainPage = self.storyboard?.instantiateViewController(withIdentifier: "ViewController")
let mainPageNav = UINavigationController(rootViewController: mainPage!)
let appDelegate = UIApplication.shared.delegate
appDelegate?.window??.rootViewController = mainPageNav
self.dismiss(animated: true, completion: nil)
} else {
// display an alert message
let userMessage = parseJSON["message"] as? String
let myAlert = UIAlertController(title: "Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler:nil)
myAlert.addAction(okAction);
self.present(myAlert, animated: true, completion: nil)
}
}
} catch
{
print(error)
}
}
}
I'm trying to get the weather of some locations using https://developer.forecast.io/ api.
The format of API call is https://api.forecast.io/forecast/APIKEY/LATITUDE,LONGITUDE
I can get response from one position, but when I tried to change the location and get the weather again use NSURL, the NSURL returns Nil. Why is that and how to handle this?
Can anyone helps me out? Thanks.
func getCurrentWeatherData() -> Void {
let baseURL = NSURL(string: "https://api.forecast.io/forecast/\(apiKey)/")
var forecastURL = NSURL(string: "36.107728,-112.113040", relativeToURL: baseURL)
let sharedSession = NSURLSession.sharedSession()
let downloadTask: NSURLSessionDownloadTask = sharedSession.downloadTaskWithURL(forecastURL!, completionHandler: {
(location: NSURL!, response: NSURLResponse!, error: NSError!) -> Void in
//var urlContents = NSString(contentsOfURL: location, encoding: NSUTF8StringEncoding, error: nil)
if (error == nil) {
let dataObject = NSData(contentsOfURL: location)
let weatherDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataObject!, options: nil, error: nil) as NSDictionary
let currentWeather = Current(weatherDictionary: weatherDictionary)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.iconView.image = currentWeather.icon!
self.currentTimeLabel.text = "At \(currentWeather.currentTime!) it is"
self.temperatureLabel.text = "\(Double(currentWeather.temperature-32) * 0.56)"
self.summaryLabel.text = "\(currentWeather.summary)"
self.refreshActivityIndicator.stopAnimating()
self.refreshActivityIndicator.hidden = true
self.refreshButton.hidden = false
})
} else {
let networkIssueController = UIAlertController(title: "Error", message:"Unable to load data. Connectivity error!", preferredStyle: .Alert)
let okButton = UIAlertAction(title: "OK", style: .Default, handler:nil)
networkIssueController.addAction(okButton)
let cancelButton = UIAlertAction(title:"Cancel", style: .Cancel, handler:nil)
networkIssueController.addAction(cancelButton)
self.presentViewController(networkIssueController, animated: true, completion: nil)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.refreshActivityIndicator.stopAnimating()
self.refreshActivityIndicator.hidden = true
self.refreshButton.hidden = false
})
}
})
downloadTask.resume()
var forecastURL2 = NSURL(string: "https://api.forecast.io/forecast/\(apiKey)/36.861941, -111.374420")
let sharedSession2 = NSURLSession.sharedSession()
**//forcastURL2 returns Nil**
let downloadTask2: NSURLSessionDownloadTask = sharedSession2.downloadTaskWithURL(forecastURL2!, completionHandler: {
(location: NSURL!, response: NSURLResponse!, error: NSError!) -> Void in
//var urlContents = NSString(contentsOfURL: location, encoding: NSUTF8StringEncoding, error: nil)
if (error == nil) {
let dataObject = NSData(contentsOfURL: location)
let weatherDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataObject!, options: nil, error: nil) as NSDictionary
let currentWeather = Current(weatherDictionary: weatherDictionary)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.iconView2.image = currentWeather.icon!
self.temperatureLabel2.text = "\(Double(currentWeather.temperature-32) * 0.56)"
self.summaryLabel.text = "\(currentWeather.summary)"
self.refreshActivityIndicator.stopAnimating()
self.refreshActivityIndicator.hidden = true
self.refreshButton.hidden = false
})
} else {
let networkIssueController = UIAlertController(title: "Error", message:"Unable to load data. Connectivity error!", preferredStyle: .Alert)
let okButton = UIAlertAction(title: "OK", style: .Default, handler:nil)
networkIssueController.addAction(okButton)
let cancelButton = UIAlertAction(title:"Cancel", style: .Cancel, handler:nil)
networkIssueController.addAction(cancelButton)
self.presentViewController(networkIssueController, animated: true, completion: nil)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.refreshActivityIndicator.stopAnimating()
self.refreshActivityIndicator.hidden = true
self.refreshButton.hidden = false
})
}
})
downloadTask2.resume()
}
The URL that you use ("https://api.forecast.io/forecast/\(apiKey)/36.861941, -111.374420") should be well formatted and, according to Apple, comply with RFC2396. If not NSURL will return nil.
The url that you use is not correct. For example space should be escape using "%20". In your case, I think you can just remove the space.
Delete the space:
var forecastURL2 = NSURL(string: "https://api.forecast.io/forecast/\(apiKey)/36.861941,-111.374420")
Also, for future questions, it would be helpful if you didn't post all of the code in your method, but rather just the code necessary to reproduce the issue (in this case, just this one line was necessary.)