Activity Indicator called from another class not Stopping - swift3

I am using activity indicator from "https://github.com/erangaeb/dev-notes/blob/master/swift/ViewControllerUtils.swift". I tried using it in my view but indicator doesn't seem to stop.I have included it in my view as below:
ActivityIndicatorView().showActivityIndicator(uiView: self.view)
I using the below code to stop:
ActivityIndicatorView().hideActivityIndicator(uiView: self.view)
But I don't know why the indicator is stoping.
More of my code is as below:
Alamofire.request(diaryViewUrl, method: .get, parameters: [:]).responseJSON {
response in
if response.result.isSuccess{
ActivityIndicatorView().showActivityIndicator(uiView: self.view)
let dataFetched : JSON = JSON(response.result.value!)
self.diaryDateTimeText = dataFetched["diary_datetime"].string
self.diaryLocText = dataFetched["diary_loc"].string
self.diaryText = dataFetched["diary_text"].string
self.diaryTags = dataFetched["tags"].arrayObject as? [String]
ActivityIndicatorView().hideActivityIndicator(uiView: self.view)
self.topBar()
self.showViews()
self.scrollView.addSubview(self.containerView)
self.view.addSubview(self.scrollView)
}else{
print("Error \(String(describing: response.result.error))")
}
}

You have to show the activity indicator before making the Alamofire request and when you get the response with success or error status you can hide it, now show and hide are called at the same time.

It works fine for me. Please try it
ActivityIndicatorView().showActivityIndicator(uiView: self.view)
Alamofire.request(diaryViewUrl, method: .get, parameters: [:]).responseJSON {
response in
ActivityIndicatorView().hideActivityIndicator(uiView: self.view)
if response.result.isSuccess{
let dataFetched : JSON = JSON(response.result.value!)
self.diaryDateTimeText = dataFetched["diary_datetime"].string
self.diaryLocText = dataFetched["diary_loc"].string
self.diaryText = dataFetched["diary_text"].string
self.diaryTags = dataFetched["tags"].arrayObject as? [String]
self.topBar()
self.showViews()
self.scrollView.addSubview(self.containerView)
self.view.addSubview(self.scrollView)
}else{
print("Error \(String(describing: response.result.error))")
}
}

Related

Alamofire AFError invalidURL

Im not able to find where i have gone wrong.I tried all possible solutions but nothing seems to work.
Can anyone suggest where I have gone wrong?
My code is as below:
var diaryEntryUrl = "http://myUrl?uid=10001&diary_text=\(textPrint)&location=\(loactionAddrEnc)"
// var diaryEntryUrl = diaryEntryUrlEncode.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) --- tried encoding, but didn't work
let postParameters:[String: Any] = [ "imagesName": self.awsImageArray2, "tagsList": self.tagArray]
Alamofire.request(diaryEntryUrl, method: .post, parameters: postParameters, encoding: JSONEncoding.default, headers: [:]).responseJSON {
response in
if response.result.isSuccess{
print("SuccessFully Added")
}else{
print("Error \(String(describing: response.result.error))")
}
}
I tried encoding the texts also but still error is there.I did it as below:
loactionAddrEnc = loactionAddr.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
var textPrint = diaryEntryText.text.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
I am getting the follwing error:
As you can see in the log Optional for location and diary text. So it means you need to unwrap it first.
if let textPrint = textPrint, let loactionAddrEnc = loactionAddrEnc {
var diaryEntryUrl = "http://myUrl?uid=10001&diary_text=\(textPrint)&location=\(loactionAddrEnc)"
// rest of your code
}
This should solve your problem. But there is another way.
You can pass all your query params in postParameters.
var diaryEntryUrl = "http://myUrl"
var postParameters:[String: Any] = [ "imagesName": self.awsImageArray2, "tagsList": self.tagArray]
postParameters["uid"] = "10001"
if let textPrint = textPrint {
postParameters["diary_text"] = textPrint
}
if let loactionAddrEnc = loactionAddrEnc {
postParameters["location"] = loactionAddrEnc
}
Alamofire.request(diaryEntryUrl, method: .post, parameters: postParameters, encoding: JSONEncoding.default, headers: [:]).responseJSON {
response in
if response.result.isSuccess {
print("SuccessFully Added")
}else{
print("Error \(String(describing: response.result.error))")
}

Json parsing in Swift 3.0

This is my code for Jason parsing in Swift:
static func POST(url: String, parameters: NSDictionary, completionBlock: #escaping CompletionBlock){
let todoEndpoint: String = Webservices.Base_Url.appending(url)
guard let url = NSURL(string: todoEndpoint) else {
print("Error: cannot create URL")
return
}
var request = URLRequest(url: url as URL)
//var request = URLRequest(url: NSURL(string: todosEndpoint)! as URL)
let session = URLSession.shared
request.httpMethod = "POST"
var err: NSError?
let jsonData = try? JSONSerialization.data(withJSONObject: parameters)
request.httpBody = jsonData
request.addValue("application/x-www-form-urlencoded;charset=UTF-8 ", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTask(with: request, completionHandler: {data, response, error -> Void in
guard error == nil else {
print("error calling POST on /todos/1")
print(error)
return
}
// make sure we got data
guard let dataTemp = data else {
print("Error: did not receive data")
return
}
// parse the result as JSON, since that's what the API provides
do {
guard let todo = try JSONSerialization.jsonObject(with: dataTemp, options: []) as? [String: AnyObject] else {
print("error trying to convert data to JSON")
return
}
// now we have the todo, let's just print it to prove we can access it
print("The todo is: " , todo)
// the todo object is a dictionary
// so we just access the title using the "title" key
// so check for a title and print it if we have one
} catch {
print("error trying to convert data to JSON")
return
}
})
task.resume()
}
I got while jason parsing:
error expression produced error: error: Execution was interrupted,
reason: EXC_BAD_ACCESS (code=1, address=0x0). The process has been
returned to the state before expression evaluation.
What's wrong?

Getting 100x100 profile pic using Facebook API, Firebase and Swift

My project had been getting the URL string for the medium sized profile pic using this code:
let downloadMediumPicTask = session.dataTask(with: mediumProfPictureURL) { (data, response, error)
in
// The download has finished.
if let e2 = error {
print("Error downloading profile picture: \(e2)")
} else {
if let res2 = response as? HTTPURLResponse {
print("Downloaded medium profile picture with response code \(res2.statusCode)")
if let imageData2 = data {
mediumProfilePictureUIImageFile = UIImage(data: imageData2)!
print("mediumProfilePictureUIImageFile has now been defined as: \(mediumProfilePictureUIImageFile).")
} else {
print("Couldn't get image: Image is nil")
}
} else {
print("Couldn't get response code for some reason")
}
}
}
downloadMediumPicTask.resume()
It crashes here giving a 403 response code. The URL that is being referenced is an expired signature URL from Facebook. Firebase doesn't adjust to get the new appropriate URL, and it was from Firebase that I had been getting the URL. I can't figure out how to get it directly as tried below:
func getUrlOfMediumProfilePic(){
if (FBSDKAccessToken.current() != nil) {
let graphPathPart2 = "me/picture"
let paramsPart2 = ["type":"medium", "redirect":"false"]
let completionHandlerPart2 = { (connection: FBSDKGraphRequestConnection?, result: Any?, error: Error?) in
if let error = error {
print("Medium picture graph call contained an error: \(error.localizedDescription)")
return
} else {
guard connection != nil else {
print("getURLOfLargeProfilePic() function aborted bc connection failed.")
return
}
let results = result! as! NSDictionary
let dataDict = results["data"] as! NSDictionary
stringOfMediumProfilePicURLaka100x100 = dataDict["url"] as! String
print("medium picture graph call results define stringOfMediumProfilePicURLaka100x100 as: \(stringOfMediumProfilePicURLaka100x100)")
}
}
let graphRequest = FBSDKGraphRequest(graphPath: graphPathPart2, parameters: paramsPart2)!
graphRequest.start(completionHandler: completionHandlerPart2)
}else{
print("User not logged in when getURLOfMediumProfilePic() function was run.")
return
}
}
This code yields an error with code 8.
Have you tried this:
https://graph.facebook.com/{id}/picture?width=100&height=100
I don't know swift, so I can't help about syntax. I think you can make http request to url and get image.
Hope this help :)

Can anyone give me example on AFNetworking 3.0 in post method?

I am struck on it because there is no AFHTTPRequestoperation to find difficult on it. please use on afnetworking 3.0 in swift.
AFHTTPRequestoperation class removed in Afnetworking 3.0
https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-3.0-Migration-Guide
Try this:
func PostData(){
let parameters : NSMutableDictionary? = [
"UserID": String(300),
"UserProfileID": String(356)]
let manager = AFHTTPSessionManager()
let serializerRequest = AFJSONRequestSerializer()
serializerRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
manager.requestSerializer = serializerRequest
let serializerResponse = AFJSONResponseSerializer()
serializerResponse.readingOptions = JSONSerialization.ReadingOptions.allowFragments
serializerResponse.acceptableContentTypes = ((((NSSet(object: "application/json") as! Set<String>) as Set<String>) as Set<String>) as Set<String>) as Set<String>;
manager.responseSerializer = serializerResponse
manager.post(Webserive.DefaultProfile, parameters: parameters, progress: nil, success: { (task: URLSessionDataTask, responseObject: Any?) in
if (responseObject as? [String: AnyObject]) != nil {
print("responseObject \(responseObject)")
}
}) { (task: URLSessionDataTask?, error: Error) in
print("POST fails with error \(error)")
}
}
Just use Alamofire if you need to implement it on swift. Check answer here which shows example of Alamofire post method.

Try! throwing fatal error in Swift 3, issues updating from Swift 2

I am trying to parse the JSON data from my server and I am getting an error when it hits the try! statement and it is crashing. It is telling me
Code=3840 "Invalid value around character 0.
It my be because I have not updated my code correctly to Swift 3. I was having an issue with if let parse for the longest time until I switched the as to as?
#IBAction func registerButtonTapped(_ sender: Any) {
let userEmail = userEmailTextField.text;
let userPassword = userPasswordTextField.text;
let userRepeatPassword = repeatPasswordTextField.text;
// Check for empty fields
if((userEmail?.isEmpty)! || (userPassword?.isEmpty)! || (userRepeatPassword?.isEmpty)!){
//Display alert message
displayMyAlertMessage(userMessage: "All fields are required");
return;
}
//Check if passwords matech
if(userPassword != userRepeatPassword){
// Display alert message
displayMyAlertMessage(userMessage: "Passwords do not match");
return;
}
// Send user data to server side
let myUrl = URL(string: "http://");
let request = NSMutableURLRequest(url:myUrl!);
request.httpMethod = "Post";
let postString = "email=\(userEmail)&password=\(userPassword)";
//adding the parameters to request body
request.httpBody = postString.data(using: String.Encoding.utf8);
//creating a task to send the post request
let task = URLSession.shared.dataTask(with: request as URLRequest){
data, response, error in
if error != nil{
print("error=\(error)")
return
}
//parsing the reponse
//converting response to Any
let json = try! JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as? [String:Any]
//parsing JSON
if let parseJSON = json{
let resultValue = parseJSON["status"] as? String
print("result: \resultValue)")
var isUserRegistered:Bool = false;
if(resultValue=="Success") { isUserRegistered = true;}
var messageToDisplay:String = parseJSON["messsage"] as! String;
if(!isUserRegistered)
{
messageToDisplay = parseJSON["message"] as! String;
}
DispatchQueue.main.async {
//Display alert message with confirmation.
let myAlert = UIAlertController(title:"Alert", message:messageToDisplay, preferredStyle: UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title:"ok", style:UIAlertActionStyle.default){ action in
self.dismiss(animated: true, completion:nil);
}
myAlert.addAction(okAction);
self.present(myAlert, animated:true, completion:nil);
};
}
}
task.resume()
}
Please help, thanks
The reason of the error is that you are sending literal "Optional(Foo)" strings to the server via String Interpolation. userEmail and userPassword will never match and the server sends no data back. In Swift 3 you have to explicitly unwrap even implicit unwrapped optional strings.
The solution is a waterproof error handling with optional bindings
#IBAction func registerButtonTapped(_ sender: AnyObject) {
// Check for empty fields
guard let userEmail = userEmailTextField.text, !userEmail.isEmpty,
let userPassword = userPasswordTextField.text, !userPassword.isEmpty,
let userRepeatPassword = repeatPasswordTextField.text, !userRepeatPassword.isEmpty else {
//Display alert message
displayMyAlertMessage(userMessage: "All fields are required")
return
}
...
Now all relevant optionals are safely unwrapped and the server will get the right data.
Further trailing semicolons and parentheses around if conditions are not needed in Swift and use URLRequest rather than NSMutableURLRequest in Swift 3
var request = URLRequest(url:myUrl!) // var is mandatory if properties are going to be changed.
PS: In any case – as already mentioned in the comments – never use carelessly try! when receiving data from a server.