Create Order to Spree ecommerce using iOS app - spree

In my app, i want to order a product in spree e-commerce by iPhone app. I easily get the products name and their detail but while creating order for products it's return the error in html page :
<h1>
TypeError
in Spree::Api::V1::OrdersController#create
</h1>
<pre>can't convert Symbol into Integer</pre>
I m sending post request as:
NSString *str = [NSString stringWithFormat:#"http://localhost:3000/api/orders"];
NSURL *urlForBuy = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:urlForBuy];
NSString *idVariant = [NSString stringWithFormat:#"order[line_items][%d][variant_id]",0];
NSString *qnty = [NSString stringWithFormat:#"order[line_items][%d][quantity]",0];
NSString *idVariantValue = #"123456";
[request setPostValue:[NSString stringWithFormat:#"%d",[idVariantValue intValue]] forKey:idVariant];
[request setPostValue:[NSString stringWithFormat:#"%d",1] forKey:qnty];
[request setPostValue:#"<my admin token>" forKey:#"token"];
[request setRequestMethod:#"POST"];
[request setDelegate:self];
[request setDidFinishSelector:#selector(buyResponse:)];
[request setDidFailSelector:#selector(buyResponse_failed:)];
[networkQueue addOperation:request];
[networkQueue go];
Also, this url i get from REST api documentation of Spree which is: http://guides.spreecommerce.com/rest.html
Another thing I want to know what is [line_items] in this url... Also if their is any tutorial apart from above url?...Thanks in advance.

Orders are created through the API by passing in line items as shown in this test.
api_post :create, :order => {
:line_items => [
{
:variant_id => variant.to_param,
:quantity => 5
}
]
}
The line_items parameter is expected to be an array of hashes, consisting of a variant_id and a quantity field. The documentation says the request looks like this:
POST /api/orders?order[line_items][0][variant_id]=1&order[line_items[0][quantity]=5
I hope that helps you understand it better!

Related

angular regex to get last parts of an url [duplicate]

How to build the function in AngularJS to chceck the last part of the url?
My examples:
#/menu1/123/edit
#/menu2/444/create/new
#/menu3/sumbenu1/333/create/new
#/menu4/submenu2/subsubmenu1/subsubsubmenu1/543/edit
The thing is:
123 444 333 543 are the ID's which are generated outside Angular
I need to check the last parts of my url: /edit or /create/new.
The length of the url will be different (number of / inside url).
I have a controller in Angular to get the url:
.controller('urlCtrl', ['$scope', '$rootScope', '$location', function ($scope, $rootScope, $location) {
$rootScope.location = $location;
$scope.hashPath = "#" + $rootScope.location.path().toString();
}]);
I'm adding the # character to the url because later I'm comparing it with my JSON.
I tried this solution but it didn't work (I also checked another solutions from this topic and nothing happened).
Any ideas?
EDIT:
Or how to check just the edit or create inside the url?
My solution is:
var path = $location.path();
var multisearch = path.search(/create|edit|new/);
console.log("multisearch: " + multisearch);
This should give you the desired result:
window.alert(window.location.href.substr(window.location.href.lastIndexOf('/') + 1));
You could get the current URL by using: window.location.href
Then you only need to get the part after the last '/'
More efficient way:
location.pathname.split('/').slice(-1)[0]
In case of http://example.com/firstdir/seconddir/thirddir?queryparams#hash; it will give you thirddir
pathname will keep only the part of url after domain name and
before query params
split will explode the url into array separated by /
slice will give you array containing only the last item
[0] will you last item as a string (in contrast to item of an
array)

IBM Watson Alchemy news iOS SDK Swift

The IBM Watson iOS SDK using the Alchemy News service on Bluemix returns a string result which requires parsing to pull out the fields like url and cleaned title. ref: https://github.com/watson-developer-cloud/swift-sdk
I pull the string into an array and parse it in swift3 using some string methods but this is pretty ordinary and can produce unpredictable results
Is there a more elegant approach where I can access specific fields, like the url and cleaned title which I am passing to a UITableViewCell to select and segue to the url link.
sample code:
let alchemyDataNews = AlchemyDataNews(apiKey: apiKey)
let failure = { (error: Error) in print(error) }
let start = "now-14d" // 7 day ago
let end = "now" // today
let query = ["count": "15",
"dedup": "true",
"q.enriched.url.title": "[IBM]",
"return": "enriched.url.url,enriched.url.title" "enriched.url.title,enriched.url.entities.entity.text,enriched.url.entities.entity.type"]
Also I have noticed the search string [IBM] has a prefix of 0, i.e. 0[IBM] and have also seen an "A". What do these prefixes mean and where are they documented
Here is one way you can access the fields from a returned payload.
alchemyDataNews.getNews(from: "now-4d", to: "now", query: queryDict, failure: failWithError) { news in
for doc in (news.result?.docs)! {
var cleanedTitle = doc.source?.enriched?.url?.cleanedTitle
var author = doc.source?.enriched?.url?.author
var title = doc.source?.enriched?.url?.title
}}
Also, here is a nice API reference link for alchemy data which contains all of the request parameters and filters.
https://www.ibm.com/watson/developercloud/alchemydata-news/api/v1/

how to display absolute url of a websevice in play framework

I am new to play framework. I am having a web service url. To that url I am appending some parameters. I want display that url after appending the values to that url.
Here is my code:
public JsonNode getCustomerDetails(CustomerDto customerDto){
String feedUrl = Constants.ERP_CUSTOMER_URL;
WSRequestHolder wsHolder = null;
wsHolder = WS.url(feedUrl);
wsHolder.setAuth(Constants.ERPUSERNAME, Constants.ERPPASSWORD,Realm.AuthScheme.BASIC);
whereClause.append("mobileno='").append(customerDto.getMobile()).append("'")
.append(ORDER_BY_UPDATED_ASC);
wsHolder.setQueryParameter(_WHERE, whereClause.toString());``
F.Promise<WS.Response> response = wsHolder.get();
json = response.get().asJson();
}
Constants.ERP_CUSTOMER_URL is my webservice url to that I am appending mobileno. I want to display the absolute url of my webservice after appending the values to it. I tried to display wsHolder but it is displaying as play.libs.WS$WSRequestHolder#6afe06a7
You can see it with getUri() on the WS.Response object like:
response.get().map((Function) response -> {
System.out.println(response.getUri());
}
);

How can I count the amount of Facebook friends in iOS sdk?

I'm trying to figure out how to get a random userID from my friends.
is there a way to do it with "friendPickerController" ?
the only "count" method I've found is in the selection, which dosen't help.
You can get the total friend count using following method
FBRequest* friendsRequest = [FBRequest requestForMyFriends];
[friendsRequest startWithCompletionHandler: ^(FBRequestConnection *connection,
NSDictionary* result,
NSError *error) {
NSArray* friends = [result objectForKey:#"data"];
NSLOG(#"Total Friend :%#",friends.count);
}];
Just updating in case this helps anyone. While Dipak's answer worked flawlessly for me at the end, it didn't work until I added permission to retrieve the count. I added the following lines of code just before Dipak's code and it returned me the proper friend count.
NSArray *permissions = [NSArray arrayWithObjects:#"friends_about_me", nil];
[FBSession openActiveSessionWithReadPermissions:permissions
allowLoginUI:YES
completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
}];
[FBSession setActiveSession:[FBSession activeSession]];

How to get large photo URL in one API call?

I want to display large photos in my Facebook app's feed view immediately. Is it possible to get the large photo src URL from a stream/feed using one API call? The photo id is returned in the stream/feed and one can of course then supply this photo id in an additional FQL or graph API call to retrieve all the information about that photo. However, is there a way using multi-query or batch calls to get a larger photo src url using one API roundtrip?
I haven't tried this with stream/feed photos, but the generally accepted way of doing this is:
http://graph.facebook.com/{ID of object}/picture
If you want the "large" version, you would do:
http://graph.facebook.com/{ID of object}/picture?type=large
I'm not 100% sure if this would work for an actual photo (instead of a user profile picture or page profile pic), but I have a hunch it will - the only caveat is that you obviously must have a logged in user that is authorized to view the photo (unless it's public).
If anybody is looking to this and type large is not enough, I found other solutions.
Type large is kind of small anyway (close to 200px). You can get larger image by adding i.e. ?width=1000 or ?height=1000. Facebook will return picture closest to given dimension and preserve aspect ratio. When passing both dimenstions like ?width=1000&height=1000, facebook will cut image to given dimensions (in this case square).
Use Facebook UserId (Oject ID) to get the picture.
https://graph.facebook.com/173xxxx8635/picture?type=large&redirect=false
which returns JSON data with picture URL.
{
"data": {
"is_silhouette": false,
"url": "https://fbcdn-profile-a.akamaihd.net/xxx/xyz/1cc066a2cae3f301d"
}
}
A good trick with the new api is to get the pic_cover field from the event table and to process it according to the size you want to use
I found when I was having this trouble that it turned out to be the picture I was downloading rather than the size I was setting it.
If for example I downloaded all my photos with a request of
[FBRequestConnection startWithGraphPath:#"/me/photos?fields=created_time,name,picture&type=tagged" parameters:nil HTTPMethod:#"GET" completionHandler:^(FBRequestConnection * connection, id result, NSError *error) {
NSDictionary * userData = (NSDictionary *)result;
NSMutableArray * array = [[NSMutableArray alloc] initWithArray:userData[#"data"]];
for (NSDictionary * dict in eventsToAdd) {
UIImage * image = dict[#"picture"]
}
}];
I am using the dictionary key search "picture" as I want the picture.
This though will get me a lower quality picture than if I searched for "source" in this search:
[FBRequestConnection startWithGraphPath:#"/me/photos?fields=created_time,name,source&type=tagged" parameters:nil HTTPMethod:#"GET" completionHandler:^(FBRequestConnection * connection, id result, NSError *error) {
NSDictionary * userData = (NSDictionary *)result;
NSMutableArray * array = [[NSMutableArray alloc] initWithArray:userData[#"data"]];
for (NSDictionary * dict in eventsToAdd) {
UIImage * image = dict[#"source"]
}
}];
If you go on the Facebook API explorer and search for photos and then click on the picture and source jpg links you can see the difference in size and quality.
Since changing this method I have managed to get rid of using the type parameters as it doesn't seem to make a different.
Note: I am using iPhone and not iPad or a larger screen so I don't know how this affects bigger screens.
The answer by #streetlogics works fine but only on pictures that have {object_id}.
http://graph.facebook.com/{object_id}/picture
But I also wanted large pictures for the feed's shared links, which sometimes don't have {object_id}. I finally realized that the {picture} thumbnail URL contains the encoded URL for the original site's large image:
https://external.xx.fbcdn.net/safe_image.php?d=AQBe9UvGd0vPbAHP&w=130&h=130&url=http%3A%2F%2Fskift.com%2Fwp-content%2Fuploads%2F2015%2F12%2Fpollution.jpg&cfs=1
--> contains -->
http://skift.com/wp-content/uploads/2015/12/pollution.jpg
So I made a loop that checks for {object_id} and if not present then extracts the URL from {picture}:
if(isset($post['object_id'])) {
echo "http://graph.facebook.com/".$post['object_id']."/picture";
}
elseif(isset($post['picture'])) {
echo urldecode(preg_replace('/&cfs.*/', '', preg_replace('/.*url=/', '', $post['picture'])));
}
else {
echo "no_large_image";
}