Swift 3.0 and web service - ios

Attempting to read our web service into a UITableViewController and it only returns the first record to the simulator. So hoping that someone will be able to look at the code and guide me down the correct path. Ultimate goal is to get it into a UITableViewCell so I can format nicely but just looking to get all the records.
Here is a view of the partial json file that will be returned.
{
"Count":11518,
"Result":[
{
"cuName": "#1",
"charter_Num":
"16328","City":
"Jonesboro",
"State_id": "GA",
"cuName_location": "#1 - Jonesboro, GA"
},
{
"cuName": "#lantec Financial",
"charter_Num": "7965",
"City": "Virginia Beach",
"State_id": "VA",
"cuName_location": "#lantec Financial - Virginia Beach, VA"
}]
}
Here is the code that reads in the json web service and attempts to parse and put in the table.
func get_data_from_url(_ link:String)
{
let url:URL = URL(string: link)!
let session = URLSession.shared
let request = NSMutableURLRequest(url: url)
request.httpMethod = "GET"
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
let task = session.dataTask(with: request as URLRequest, completionHandler: {
(
data, response, error) in
guard let _:Data = data, let _:URLResponse = response , error == nil else {
return
}
self.extract_json(data!)
})
task.resume()
}
func extract_json(_ data: Data)
{
let json: Any?
do
{
json = try JSONSerialization.jsonObject(with: data, options: [])
}
catch
{
return
}
//Commented out the following lines because it doesn't return anything when using the modified code that works
//
// guard let data_list = json as? NSArray else
// {
// return
// }
//This code works but only gives me the 1st record back
if let cu_list = try? json as? [String:Any],
let result = cu_list?["Result"] as? [[String:Any]],
let charter_num = result[0]["charter_Num"] as? String,
let value = result[0]["cuName_location"] as? String, result.count > 0 {
TableData.append(value + " (" + charter_num + ")")
} else {
print("bad json - do some recovery")
}
DispatchQueue.main.async(execute: {self.do_table_refresh()})
}

You are referring the 0th index element from result object and it will only return the 1st record from JSON data. You need to run thru the loop and append the data to array which you need to use for populating the data in UITableView.

func GetCategoryData(){
//get_high_score.php?from=1472409001482&number=10&to=1493657787867
let checklaun = UserDefaults.standard.integer(forKey: "Language")
if checklaun == 1 {
EZLoadingActivity.show("Loading...", disableUI: false)
}else{
EZLoadingActivity.show("جار التحميل...", disableUI: false)
}
DispatchQueue.global(qos: .background).async {
let myUrl = URL(string: GlobleUrl.BASEURL + "advertise_list.php");
var request = URLRequest(url:myUrl!)
request.httpMethod = "GET"
// let fromvalue = 1472409001482
// let numbervalue = 10
// let tovalue = 1493657787867
let postString = ""//"from=" + fromvalue + "&" + "number=" + numbervalue + "&" + "to=" + tovalue
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil
{
EZLoadingActivity.hide(false, animated: true)
print("error=\(error)")
let checklaun = UserDefaults.standard.integer(forKey: "Language")
var titlemsga : String = String()
var okmsg : String = String()
if checklaun == 1 {
titlemsga = "Something going wrong"
okmsg = "Ok"
}else{
titlemsga = "حدث خطأ ما"
okmsg = "حسنا"
}
let alert = UIAlertController(title: "", message: titlemsga, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: okmsg, style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
return
}
print("response = \(response)")
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
DispatchQueue.main.async {
if let parseJSON = json {
print(parseJSON)
let status = parseJSON["status"] as! Bool
if status == true{
EZLoadingActivity.hide(true, animated: false)
self.categoryDataArray = parseJSON["data"] as! NSMutableArray
print("\(self.categoryDataArray)")
self.filterarray = parseJSON["fixed_cat"] as! NSMutableArray
let teamp = self.categoryDataArray .value(forKey: "main_image") as AnyObject
print("\(teamp)")
self.categoryImageArray.setArray(teamp as! [Any])
print("\( self.categoryImageArray)")
// let teamp = self.data .value(forKey: "name") as AnyObject
// print("\(teamp)")
// self.categoryNameArray.setArray(teamp as! [Any])
self.allcategoryTableViewCell.reloadData()
self.allcategoryfilterlistview.reloadData()
// self.tblscoreList.reloadData()
}else{
EZLoadingActivity.hide(false, animated: true)
}
}
}
}
catch {
EZLoadingActivity.hide(false, animated: true)
let checklaun = UserDefaults.standard.integer(forKey: "Language")
var titlemsga : String = String()
var okmsg : String = String()
if checklaun == 1 {
titlemsga = "Something going wrong"
okmsg = "Ok"
}else{
titlemsga = "حدث خطأ ما"
okmsg = "حسنا"
}
let alert = UIAlertController(title: "", message: titlemsga, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: okmsg, style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
print(error)
}
}
task.resume()
}
}

Related

Webservice method not getting the value for the first click

in this i am getting the value through webservice. it's getting the value perfectly. for testing i used print statement and it's showing prefect values, but when i am assigning those values to variable it's not assgning on second click my variable are getting the values.. first time it goes in else, however it should go in if.
let task = URLSession.shared.dataTask(with: url!) {(data, response, error) in
if error != nil
{
print("Error")
}
else
{
if let content = data
{
do
{
let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
let asd = myJson.value(forKey: "signinResult")
print(asd!)
self.answer = String(describing: asd!)
var mystring = self.answer.components(separatedBy:"\"")
var mystrin = [String]()
let size = mystring.count
var i = 0
while (i < size-1 )
{
let st1 = mystring[i+1]
mystrin = st1.components(separatedBy:",")
self.em = mystrin[0]
print(self.em)
self.pw = mystrin[1]
print(self.pw)
self.na = mystrin[2]
print(self.na)
self.num = mystrin[3]
print (self.num)
i += 2
}
}
catch
{
}
}
}
task.resume()
if email.text == em && pwd.text == pw
{
GlobalVariable.myString=em
GlobalVariable.name=na
GlobalVariable.number=num
GlobalVariable.pwd = pw
GlobalVariable.i=1
self.performSegue(withIdentifier: "segue", sender: nil)
}
else
{
let alert = UIAlertController(title: "Alert", message: "Wrong Email and password", preferredStyle:UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
self.present(alert,animated: true, completion: nil)
}
You set value of that variable in web service block but using it outside the block so first time it doesn't have value to show when you click send time meanwhile web service response and value assign to that variable so get it.
The code should be like this.
let task = URLSession.shared.dataTask(with: url!) {(data, response, error) in
if error != nil
{
print("Error")
}
else
{
if let content = data
{
do
{
let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
let asd = myJson.value(forKey: "signinResult")
print(asd!)
self.answer = String(describing: asd!)
var mystring = self.answer.components(separatedBy:"\"")
var mystrin = [String]()
let size = mystring.count
var i = 0
while (i < size-1 )
{
let st1 = mystring[i+1]
mystrin = st1.components(separatedBy:",")
self.em = mystrin[0]
print(self.em)
self.pw = mystrin[1]
print(self.pw)
self.na = mystrin[2]
print(self.na)
self.num = mystrin[3]
print (self.num)
i += 2
}
if email.text == em && pwd.text == pw
{
GlobalVariable.myString=em
GlobalVariable.name=na
GlobalVariable.number=num
GlobalVariable.pwd = pw
GlobalVariable.i=1
self.performSegue(withIdentifier: "segue", sender: nil)
}
else
{
let alert = UIAlertController(title: "Alert", message: "Wrong Email and password", preferredStyle:UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
self.present(alert,animated: true, completion: nil)
}
}
catch
{
}
}
}
task.resume()

OAuth2, Swift 3, Instagram

There seem to be lots of changes at IG. Many OAuth2 repos, all seem to have bugs, or really not easily converted to Swift3. Wondering if anyone has a solution for moving to Swift3 and working with the latest changes at Instagram?
Solutions most welcome. OAuth2 implementation seems to one of the more complicated things out there. Surprised that IG has not offered their own example docs on how to do this with iOS. They only have docs for web based solutions.
Maybe something brewing there? Zillions of coders they have on staff. But for now, on the hunt for a (dare I say?) simple solution.
thanks a million. :-)
For Swift 3:
Update: April 17 2017: Because of broken dependencies, the installation by Pods is no longer working. Therefore I have ripped the needed content and created a new Github project using a Bridging Header and stored all the needed files within the project. If you clone or download the github project, you'll instantly be able to login to Instagram.
To use those files in your project, simply drag and drop all the files from the SimpleAuth folder to your project, make sure to mark copy item if needed
Also you need to disable Disable implicit oAuth within the Instagram developer console.
Then you either copy/paste my code from the Bridging Header into your or you use mine. Set the Bridging Header at the Target's Build Settings.
Everything else works as before:
I have a struct for the Instagram Account:
struct InstagramUser {
var token: String = ""
var uid: String = ""
var bio: String = ""
var followed_by: String = ""
var follows: String = ""
var media: String = ""
var username: String = ""
var image: String = ""
}
The function to receive the token:
typealias JSONDictionary = [String:Any]
var user: InstagramUser?
let INSTAGRAM_CLIENT_ID = "16ee14XXXXXXXXXXXXXXXXXXXXXXXXX"
let INSTAGRAM_REDIRECT_URI = "http://www.davidseek.com/just_a_made_up_dummy_url" //just important, that it matches your developer account uri at Instagram
extension ViewController {
func connectInstagram() {
let auth: NSMutableDictionary = ["client_id": INSTAGRAM_CLIENT_ID,
SimpleAuthRedirectURIKey: INSTAGRAM_REDIRECT_URI]
SimpleAuth.configuration()["instagram"] = auth
SimpleAuth.authorize("instagram", options: [:]) { (result: Any?, error: Error?) -> Void in
if let result = result as? JSONDictionary {
var token = ""
var uid = ""
var bio = ""
var followed_by = ""
var follows = ""
var media = ""
var username = ""
var image = ""
token = (result["credentials"] as! JSONDictionary)["token"] as! String
uid = result["uid"] as! String
if let extra = result["extra"] as? JSONDictionary,
let rawInfo = extra ["raw_info"] as? JSONDictionary,
let data = rawInfo["data"] as? JSONDictionary {
bio = data["bio"] as! String
if let counts = data["counts"] as? JSONDictionary {
followed_by = String(describing: counts["followed_by"]!)
follows = String(describing: counts["follows"]!)
media = String(describing: counts["media"]!)
}
}
if let userInfo = result["user_info"] as? JSONDictionary {
username = userInfo["username"] as! String
image = userInfo["image"] as! String
}
self.user = InstagramUser(token: token, uid: uid, bio: bio, followed_by: followed_by, follows: follows, media: media, username: username, image: image)
} else {
// this handles if user aborts or the API has a problem like server issue
let alert = UIAlertController(title: "Error!", message: nil, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
if error != nil {
print("Error during SimpleAuth.authorize: \(error)")
}
}
}
}
Instagram also says:
Important
Even though our access tokens do not specify an expiration time, your
app should handle the case that either the user revokes access, or
Instagram expires the token after some period of time. If the token is
no longer valid, API responses will contain an
“error_type=OAuthAccessTokenException”. In this case you will need to
re-authenticate the user to obtain a new valid token. In other words:
do not assume your access_token is valid forever.
So handle the case of receiving the OAuthAccessTokenException
This Code bellow I use for facebook and google+, I think it'ill work for Instagram too, maybe some adjusts.
import UIKit
class Signup: UIViewController, UIWebViewDelegate {
let GOOGLE_ID = "xxxxxx.apps.googleusercontent.com"
let GOOGLE_SECRET = "xxxxxxx";
let GOOGLE_REDIRECT_URI="http://yourdomain.com/api/account/googlecallback"
let GOOGLE_TOKEN_URL = "https://accounts.google.com/o/oauth2/token";
let GOOGLE_OAUTH_URL = "https://accounts.google.com/o/oauth2/auth";
let GOOGLE_OAUTH_SCOPE = "profile email";
let GOOGLE_GET_PROFILE = "https://www.googleapis.com/userinfo/v2/me";
let FACEBOOK_ID = "xxxxx";
let FACEBOOK_REDIRECT_URI = "http://yourdomain.com/api/account/facebookcallback";
let FACEBOOK_OAUTH_URL = "https://www.facebook.com/dialog/oauth?client_id=";
let FACEBOOK_OAUTH_SCOPE = "public_profile,email"
let FACEBOOK_GET_PROFILE = "https://graph.facebook.com/me?access_token="
var currentURL: String = ""
var queryString: String = ""
var receivedToken: String = ""
var authCode: String = ""
var authComplete = false
var webV:UIWebView = UIWebView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
#IBAction func google(_ sender: AnyObject) {
AppVars.Provider = "Google"
webV.delegate = self
let url = GOOGLE_OAUTH_URL + "?redirect_uri=" + GOOGLE_REDIRECT_URI + "&response_type=code&client_id=" + GOOGLE_ID + "&scope=" + GOOGLE_OAUTH_SCOPE
let urlString :String = url.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
webV.loadRequest(URLRequest(url: URL(string:urlString)!))
self.view.addSubview(webV)
}
#IBAction func facebook(_ sender: AnyObject) {
AppVars.Provider = "Facebook"
webV.delegate = self
let url = FACEBOOK_OAUTH_URL + FACEBOOK_ID + "&redirect_uri=" + FACEBOOK_REDIRECT_URI + "&scope=" + FACEBOOK_OAUTH_SCOPE + "&display=popup&response_type=token"
let urlString :String = url.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
webV.loadRequest(URLRequest(url: URL(string:urlString)!))
self.view.addSubview(webV)
}
func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
self.showAlert(self, message: "Internet is not working")
}
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
return true;
}
func webViewDidStartLoad(_ webView: UIWebView) {
}
func webViewDidFinishLoad(_ webView: UIWebView) {
currentURL = (webView.request?.url!.absoluteString)!
if AppVars.Provider == "Google" {
googleSignup((webView.request?.url!)!)
} else {
facebookSignup((webView.request?.url!)!)
}
}
func googleSignup (_ returnCode: URL) {
let url = String(currentURL)
if (url?.range(of: "?code=") != nil && authComplete != true) {
authCode = getQueryItemValueForKey("code", url: returnCode)!
authComplete = true
let paramString = "code=" + authCode + "&client_id=" + GOOGLE_ID + "&client_secret=" +
GOOGLE_SECRET + "&redirect_uri=" + GOOGLE_REDIRECT_URI + "&grant_type=authorization_code"
self.requestServer(urlSource: GOOGLE_TOKEN_URL, params: paramString, requestType: "POST") { (dataResult, errorResult) -> () in
if errorResult != nil {
self.showAlert(self, message: "Internet is not working")
} else {
let dataString:NSString = NSString(data: dataResult as! Data, encoding: String.Encoding.utf8.rawValue)!
let dataResult2 = dataString.data(using: String.Encoding.utf8.rawValue, allowLossyConversion: false)!
do {
let jsonDict = try JSONSerialization.jsonObject(with: dataResult2, options: .allowFragments) as! [String:Any]
if let token = jsonDict["access_token"] as? String {
self.requestServerSignup(self.GOOGLE_GET_PROFILE, param: token, requestType: "GET") { (dataResult, errorResult) -> () in
if errorResult != nil {
self.showAlert(self, message: "Internet is not working")
} else {
let dataString:NSString = NSString(data: dataResult as! Data, encoding: String.Encoding.utf8.rawValue)!
let dataResult2 = dataString.data(using: String.Encoding.utf8.rawValue, allowLossyConversion: false)!
do {
let jsonDict = try JSONSerialization.jsonObject(with: dataResult2, options: .allowFragments) as! [String:Any]
if let name = jsonDict["name"] as? String {
AppVars.NameLogin = name
AppVars.PictureLogin = jsonDict["picture"] as! String
AppVars.EmailLogin = jsonDict["email"] as! String
self.performSegue(withIdentifier: "externalLoginSegue", sender: self)
// show picture, email and name for checking profile
}
} catch {
self.showAlert(self, message: "Internet is not working")
}
}
}
}
} catch {
self.showAlert(self, message: "Internet is not working")
}
}
}
self.webV.removeFromSuperview()
}
}
func facebookSignup(_ returnCode: URL) {
let url = String(currentURL)
if (url?.range(of: "access_token=") != nil && authComplete != true) {
let url2: String = returnCode.absoluteString.replacingOccurrences(of: "#access_token", with: "access_token")
let url3: URL = URL(string: url2)!
authCode = getQueryItemValueForKey("access_token", url: (url3))!
authComplete = true
let paramString = "code=" + authCode + "&client_id=" + GOOGLE_ID + "&client_secret=" +
GOOGLE_SECRET + "&redirect_uri=" + GOOGLE_REDIRECT_URI + "&grant_type=authorization_code"
self.requestServer(urlSource: self.FACEBOOK_GET_PROFILE + authCode + "&fields=name,picture,email", params: paramString, requestType: "GET") { (dataResult, errorResult) -> () in
if errorResult != nil {
self.showAlert(self, message: "Internet is not working")
} else {
let dataString:NSString = NSString(data: dataResult as! Data, encoding: String.Encoding.utf8.rawValue)!
let dataResult2 = dataString.data(using: String.Encoding.utf8.rawValue, allowLossyConversion: false)!
do {
let jsonDict = try JSONSerialization.jsonObject(with: dataResult2, options: .allowFragments) as! [String:Any]
if let name = jsonDict["name"] as? String {
AppVars.NameLogin = name
if let picture = jsonDict["picture"] as? [String:Any] {
if let dataPicture = picture["data"] as? [String:Any] {
if let url = dataPicture["url"] as? String {
AppVars.PictureLogin = url
}
}
}
AppVars.EmailLogin = jsonDict["email"] as! String
self.performSegue(withIdentifier: "externalLoginSegue", sender: self)
// show picture, email and name for checking profile
}
} catch {
self.showAlert(self, message: "Internet is not working")
}
}
}
self.webV.removeFromSuperview()
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func getQueryItemValueForKey(_ key: String, url: URL) -> String? {
guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false) else {
return nil
}
guard let queryItems = components.queryItems else { return nil }
return queryItems.filter {
$0.name == key
}.first?.value
}
func requestServer(urlSource:String, params:String, requestType:String, result:#escaping (_ dataResult:NSData?, _ errorResult:NSError?) -> ()) {
let url: URL = URL(string: urlSource)!
var request = URLRequest(url:url)
request.httpMethod = requestType
request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
if params.characters.count > 0 {
request.httpBody = params.data(using: String.Encoding.utf8)
}
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) -> Void in
DispatchQueue.main.async(execute: { () -> Void in
if error == nil {
result(data as NSData?, nil)
} else {
result(nil, error as NSError?)
}
})
}.resume()
}
}

Json response error handling

My app has a search bar that sends a query to a MySQL database and then receives a JSON response and displays it in a view. This works great when the response is success (there's an actual array and rows in MySQL). However, when the response is empty I would like to display an alertbox with a simple error.
My PHP code on the server is set to echo No rows when the query response is empty, how can I achieve this in my app?
This is what I have going right now:
func searchBarSearchButtonClicked(searchBar: UISearchBar)
{
if(searchBar.text!.isEmpty)
{
return
}
doSearch(searchBar.text!)
}
func doSearch(searchWord: String)
{
mySearchBar.resignFirstResponder()
//created NSURL
if let requestURL = NSURL(string: URL_GET_coffees) {
//creating NSMutableURLRequest
let request = NSMutableURLRequest(URL: requestURL)
//setting the method to post
request.HTTPMethod = "POST"
//getting values from search bar text field
let searchText=mySearchBar.text
//creating the post parameter from search bar text field
let postParameters = "searchQuery="+searchText!;
//adding the parameters to request body
request.HTTPBody = postParameters.dataUsingEncoding(NSUTF8StringEncoding)
//creating a task to send the post request
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
data, response, error in
//exiting if there is some error
if error != nil{
print("error is \(error)")
self.displayAlertMessage(error!.localizedDescription)
return;
}
//parsing the response
do {
guard let coffees = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSArray else {
//Doesn't exist, or isn't an NSArray
return
}
var newcoffees=[face]()
for coffee in coffees {
//getting the data at each index
let coffeeName = coffee["name"] as! String
let coffeeDirectLink = coffee["calculation_toemail_"] as! String
let coffeeImage = coffee["calculation_toemail_"] as! String
let newface = face(name:coffeeName,
directLink: coffeeDirectLink,
image:coffeeImage)
newcoffees.append(newface)
//displaying the data
print("name -> ", coffeeName)
print("direct_link -> ", coffeeDirectLink)
print("image -> ", coffeeImage)
print("===================")
print()
}
dispatch_async(dispatch_get_main_queue(),{
self.faces = newcoffees
self.collectionview.reloadData()
})
let errorMessage = newcoffees["No rows"] as? String
if(errorMessage != nil)
{
// display an alert message
self.displayAlertMessage(errorMessage!)
}
} catch {
print(error)
}
}
//executing the task
task.resume()
}
}
func displayAlertMessage(userMessage: 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.presentViewController(myAlert, animated: true, completion: nil)
}
But what's going on is I'm getting an Cannot subscript a value of type '[face]' with an index of type 'String' where I tell it what the error response is. What can I be doing wrong?

NSURLSession.sharedSession().dataTaskWithRequest runs slow in function

My problem arises when I want to populate data from my mysql database into a class object. I am trying to return an array of objects and it returns nil and then it fills itself somehow. How can I make it fill before returning the blank array?
Here is my code and a screenshot of code output
import Foundation
class Research
{
var mainResearchImageURL:String = ""
var userProfileImageURL:String = ""
var caption:String = ""
var shortDescription:String = ""
init(mainResearchImageURL :String, userProfileImageURL:String, caption:String, shortDescription:String)
{
self.mainResearchImageURL = mainResearchImageURL
self.userProfileImageURL = userProfileImageURL
self.caption = caption
self.shortDescription = shortDescription
}
class func downloadAllResearches()->[Research]
{
var researches = [Research]()
let urlString = "http://localhost/test/index.php"
let request = NSMutableURLRequest(URL: NSURL(string: urlString)!)
request.HTTPMethod = "POST"
let postString = "action=listresearches"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: {data, response, error in
if (error == nil) {
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSArray
//let dictionary = json!.firstObject as? NSDictionary
var counter:Int = 0;
for line in json!{
let researchData = line as! NSDictionary
let researchLineFromData = Research(mainResearchImageURL: researchData["research_mainImageURL"] as! String, userProfileImageURL: researchData["research_creatorProfileImageURL"] as! String, caption: researchData["research_caption"] as! String, shortDescription: researchData["research_shortDescription"] as! String)
researches.append(researchLineFromData) //researches bir dizi ve elemanları Research türünde bir sınıftan oluşuyor.
counter += 1
print ("counter value \(counter)")
print("array count in loop is = \(researches.count)")
}
}catch let error as NSError{
print(error)
}
} else {
print(error)
}})
task.resume()
print("array count in return is = \(researches.count)")
return researches
}
}
And this is the output:
add this on you completionHandler ( it works if you update a view)
dispatch_async(dispatch_get_main_queue(), {
if (error == nil) { ...... }
})
Advice 1:
return the task and use a completion param in your method,
you can cancel the task if it's too slow.
Advice 2 :
Use alamofire and swiftyJson framework
What happen here is that you are returning the value before finish (remember that the call is Asynchronous), you can make something like this:
class func downloadAllResearches(success:([Research])->Void,failure:(String)->Void)
{
var researches = [Research]()
let urlString = "http://localhost/test/index.php"
let request = NSMutableURLRequest(URL: NSURL(string: urlString)!)
request.HTTPMethod = "POST"
let postString = "action=listresearches"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: {data, response, error in
if (error == nil) {
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSArray
//let dictionary = json!.firstObject as? NSDictionary
var counter:Int = 0;
for line in json!{
let researchData = line as! NSDictionary
let researchLineFromData = Research(mainResearchImageURL: researchData["research_mainImageURL"] as! String, userProfileImageURL: researchData["research_creatorProfileImageURL"] as! String, caption: researchData["research_caption"] as! String, shortDescription: researchData["research_shortDescription"] as! String)
researches.append(researchLineFromData) //researches bir dizi ve elemanları Research türünde bir sınıftan oluşuyor.
counter += 1
print ("counter value \(counter)")
print("array count in loop is = \(researches.count)")
}
success(researches)
}catch let error as NSError{
print(error)
failure("Can be extract from NSERROR")
}
} else {
print(error)
failure("Error - Can be extract for NSERROR")
}})
task.resume()
}
And for call this Fuction use something like this:
Research.downloadAllResearches({ (objects:[Research]) -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
//Do whatever you like with the content
})
}) { (failureLiteral:String) -> Void in
}

Swift Convert string into UIIMAGE

I would like to load an image from an api web service asynchronously into a uitableview with swift for iOS 9. Below is the code from my Playlist controller. Thanks in advance.
import UIKit
class PlaylistViewController: UITableViewController {
var playlists = [[String: String]]()
override func viewDidLoad() {
super.viewDidLoad()
let urlString = "http://xxxxxxx.xxx/api/v1/players/1/playlists?api_key=xxxxxxxxxxxx"
if let url = NSURL(string: urlString) {
if let data = try? NSData(contentsOfURL: url, options: []) {
let json = JSON(data: data)
if json != nil {
parseJSON(json)
} else {
showError()
}
} else {
showError()
}
} else {
showError()
}
}
func showError() {
let ac = UIAlertController(title: "Loading error", message: "There was a problem loading the feed; please check your connection and try again.", preferredStyle: .Alert)
ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
presentViewController(ac, animated: true, completion: nil)
}
func parseJSON(json: JSON) {
for result in json["playlists"].arrayValue {
let title = result["title"].stringValue
let id = result["id"].stringValue
let cover_url = result["cover_url"].stringValue
let obj = ["title": title, "id": id, "cover_url" : cover_url]
playlists.append(obj)
}
tableView.reloadData()
}
Use NSURLSession dataTaskWithURL for asynchronously task:
override func viewDidLoad() {
super.viewDidLoad()
let urlString = "http://xxxxxxx.xxx/api/v1/players/1/playlists?api_key=xxxxxxxxxxxx"
if let url = NSURL(string: urlString) {
let session = NSURLSession.sharedSession()
var task = session.dataTaskWithURL(url) { (data, response, error) -> Void in
if let err = error {
showError(err)
} else {
let json = NSString(data: data, encoding: NSUTF8StringEncoding)
// json is a String, you should handle this String as JSON
parseJSON(json)
}
}
}
Your tableView.reloadData() should be executed in main thread (because the NSURLSession dataTaskWithUrl result is in background thread)
dispatch_async(dispatch_get_main_queue(), {
tableView.reloadData()
})

Resources